views:

300

answers:

2

I'm confused regarding each() and .each()... I think I need to use both, but I'm not sure how...

Basically, I have a series of checkboxes and when they're checked, I want to get the id of the closest table row and add it to an array that I can then serialize and pass to a function.

So, the html looks like this:

<tr id="t1"><td><input type="checkbox" name="did[]" value="232" class="bd" /></td></tr>
<tr id="t2"><td><input type="checkbox" name="did[]" value="234" class="bd" /></td></tr>
<tr id="t3"><td><input type="checkbox" name="did[]" value="676" class="bd" /></td></tr>
<tr><td><button id="tsid" name="tsid" type="button">Send</button></td></tr>

And, when (and if) the checkbox is selected, I want to get the closest tr id and store it in an array:

var trids = []

And then serialize the input data and the trids array...

So far, I only have this:

$('#tsid').click(function() {

  //meant to get the values of the selected checkboxes
  var myData = $('input[name=did[]]').serialize();

  //meant to find and store the closest tr ids in an array... 
  $('.bd').each(function() {
    var trids = $(this).closest("tr").get(0);  //and now I'm lost... 
  });

}
+1  A: 

It should just be:

$('.bd:checked').each(function() {
   trids.push($(this).closest("tr").attr('id')); // instead of var trids = ....
});

$('.bd:checked') selects only the checked checkboxes. closest('tr') gets the parent tr as you already did it correctly. attr('id') gets the id of this tr. There is no need in get(0) as closest() already selects just one element.
Then this value is added to the array trids by using the push() method on the array.

Update:
jQuery's .searialize() function generates a string out of the values of form elements, e.g.:

field1=value1&field2=value2&...

I don't think it works on arrays though. The only solution I know would be generate the string for the array by yourself:

var myData = $('input[name=did[]]').serialize();

for(var i = 0; i < trids.length; i++) {
    myData += '&trid[]=' + trids[i]; or // '&trid%5B%5D=' have it encoded.
}

This would append the array values to the serialized string.
But I guess there is a better solution for this.

Felix Kling
Ohhhhhh.... Thanks for this. How do I get the trids array and the myData array into one? I tried var sData = $('input[name=dsid[]]').trids.serialize(); but, obviously... that didn't work...
KittyYoung
@KittyYoung: That depends on how you want to have the resulting array look like.
Felix Kling
KittyYoung
@KittyYoung: Not exactly but my comment was unnecessary due the fact that you want to serialize the data and `serialize()` only works on form element. See updated answer whether this helps you.
Felix Kling
A: 

Simply get the elements, then use the map function to get the id from each tr element. Use the get method to get the result as an array instead of an jQuery object.

var trids = $('.bd').map(function(i,e){ return $(e).closest('tr').attr('id'); }).get();
Guffa