Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
114
rated 0 times [  115] [ 1]  / answers: 1 / hits: 25409  / 10 Years ago, thu, july 17, 2014, 12:00:00

I have an HTML table where I need to select multiple rows and send first cell value of each row to a function. I tried the follwing code. This selects only one row and sends only one value to the function. If I select multiple rows only the first value selected is entering the function. How do I solve this issue?



test.html



<table id=table>
<tr>
<td>1 Ferrari F138</td>
<td>1 000€</td>
<td>1 200€</td>

</tr>
<tr>
<td>2 Ferrari F138</td>
<td>1 000€</td>
<td>1 200€</td>

</tr>
<tr>
<td>3 Ferrari F138</td>
<td>1 000€</td>
<td>1 200€</td>

</tr>
</table>
<input type=button class=ok id=tst value=OK onclick= />


test.js



$(#table tr).click(function(){
$(this).addClass('selected').siblings().removeClass('selected');
var value=$(this).find('td:first').html();
alert(value);
});

$('.ok').on('click', function(e){
var selectedID=$(#table tr.selected td:first).html();
fnMatchID(selectedID);

});

function fnMatchID(selectID){
//some code here
}


DEMO :::: JSFiddle



I need to select multiple rows and send all the first cell values of the selected rows to a function.


More From » jquery

 Answers
151

Depending on whether you want to call the function multiple times or send the data along as an array, there are two things you can do.



Either way, don't removeClass on .siblings(), if you want to be able to select multiple rows. You might also consider using .toggleClass(selected) instead of .addClass(selected), if you want to be able to unselect rows.



Solution 1: Send data as array of strings



$(#table tr).click(function(){
$(this).addClass('selected');
var value=$(this).find('td:first').html();
alert(value);
});

$('.ok').on('click', function(e){
var selectedIDs = [];
$(#table tr.selected).each(function(index, row) {
selectedIDs.push($(row).find(td:first).html());
});


fnMatchID(selectedIDs);

});


Solution 2: Call function repeatedly



$(#table tr).click(function(){
$(this).addClass('selected');
var value=$(this).find('td:first').html();
alert(value);
});

$('.ok').on('click', function(e){
$(#table tr.selected).each(function(index, row) {
fnMatchID($(row).find(td:first).html());
});
});


Either way, what you're probably looking for is the .each function:
http://api.jquery.com/each/


[#70176] Tuesday, July 15, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ellisw

Total Points: 625
Total Questions: 92
Total Answers: 88

Location: Kazakhstan
Member since Mon, Sep 26, 2022
2 Years ago
ellisw questions
Mon, Aug 23, 21, 00:00, 3 Years ago
Fri, Nov 20, 20, 00:00, 4 Years ago
Sat, Jun 20, 20, 00:00, 4 Years ago
Tue, Apr 21, 20, 00:00, 4 Years ago
;