lleoun lleoun - 1 month ago 8
jQuery Question

Getting separated strings from array information

The following code stores into an array the row information from the checked checkboxes of a html table:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>

<script>
function myFunc() {
var myValues = new Array();

$.each($("input[name='selection[]']:checked").closest("td").siblings("td"),
function () {
myValues.push($(this).text());
});

alert("values: " + myValues.join(" "));

}

</script>

<table border="2">
<tr>
<th>Select</th>
<th>ID</th>
<th>NAME</th>
<th>JOB</th>
</tr>
<tr>
<td align="center"><input type="checkbox" class="selection" name="selection[]"></td>
<td>11</td>
<td>John</td>
<td>Doctor</td>
</tr>
<tr>
<td align="center"><input type="checkbox" class="selection" name="selection[]"></td>
<td>102</td>
<td>Anne</td>
<td>Pilot</td>
</tr>
<tr>
<td align="center"><input type="checkbox" class="selection" name="selection[]"></td>
<td>203</td>
<td>Laura</td>
<td>Teacher</td>
</tr>

</tr>
</table>
<input type="button" value="get it" onclick="javascript:myFunc(); return false;">


Now I need to have the selected ids in a comma separated string (if all the checkboxes where selected would be:
str1="11,102,203";
)

And the ids plus the rest of the information in the selected rows in another string (if all the checkboxes where selected would be:
str2 = "11, John, Doctor,102, Anne,Pilot, 203, Laura, Teacher";
).

And I don't know how to do it. I'm thinking in adding keys to myValues array but I don't know if it is a good approach (and don't have a clue on how to do it.. too new to jquery :( )

Answer

Solved: See if this helps you

Though i am not sure how you want the 2 strings to look like, i have created a demo for you to fetch different values in a selected row. I suggest you loop over selected checkbox td and fetch different values in row using next() function.

$.each($("input[name='selection[]']:checked").closest("td"),function (index,item) {
...
});

JS Fiddle Demo http://jsfiddle.net/kTDPK/

For strings output check the console of browser.

Comments