0

I have been searching for a way to do this, and I have looked at the several questions posted on here, but I can't obtain all elements of the array I want. Here is the array I'm sending:

function myFunction(e) {
 var containerChildren = $("#active").children();
 for (i = 0; i < containerChildren.length; i++) {
 var announcementarray = new Array();
 announcementarray[i] = $('#' + containerChildren[i].id).data("id");
 alert(announcementarray[i]);
 }
 $.ajax({
 data:
 {
 activeid: announcementarray
 },
 datatype: 'json',
 url: '/HumanResources/Announcement/AnnouncementActive',
 cache: false,
 type: 'POST',
 traditional: true,
 error: function (result) {
 alert(result);
 },
 success: function (result) {
 //alert(result);
 }
 });
 }

However, whenever the controller receives this data, it only shows the last children with the an actual value, all the others are undefined . Here is the declaration of my controller

public ActionResult AnnouncementActive(string[] activeid, string[] inactiveid)
{
}

Any help is appreciated! (I have tried traditional: true, .serialize(), etc)

tereško
58.5k26 gold badges100 silver badges151 bronze badges
asked Jun 11, 2013 at 19:47
1
  • Found mistake: declaration of array is inside for loop. After taking it out of there, problem fixed! Commented Jun 11, 2013 at 20:06

1 Answer 1

4

You are recreating your array for each child element in your first selector. Try something like this:

function myFunction(e) {
 var announcementarray = [];
 $("#active").children().each(function() {
 announcementarray.push($(this).data("id"));
 });
 $.ajax({
 data:
 {
 activeid: announcementarray
 },
 datatype: 'json',
 url: '/HumanResources/Announcement/AnnouncementActive',
 cache: false,
 type: 'POST',
 traditional: true,
 error: function (result) {
 alert(result);
 },
 success: function (result) {
 //alert(result);
 }
 });
}
Mark Pieszak - Trilon.io
68.1k15 gold badges84 silver badges96 bronze badges
answered Jun 11, 2013 at 19:52

3 Comments

The elements returned from $.children(); are also jQuery objects so this could be made a little better. See my updates.
That does seem a lot less confusing. Thanks for clearing it up. However, whenever I run it, I get a runtime error saying it does not recognize 'data' (which is a property in the html 'data-*'
I'll mark your response as the answer but I found my error. I had my declaration of the array inside of the for loop. After taking it out, it works like a charm!! Thanks for your feedback!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.