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
-
Found mistake: declaration of array is inside for loop. After taking it out of there, problem fixed!Jose– Jose2013年06月11日 20:06:41 +00:00Commented Jun 11, 2013 at 20:06
1 Answer 1
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
Jay
The elements returned from $.children(); are also jQuery objects so this could be made a little better. See my updates.
Jose
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-*'
Jose
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!
lang-js