Rod Rod - 1 month ago 14
jQuery Question

How can I check the checkbox based on the text?

I want to check the checkbox based on the text in the next column. Here's how I did it, is there a more concise way?

JSFiddle

<table id="table1">
<tr><td><input type="checkbox"></td><td>Text 1</td></tr>
<tr><td><input type="checkbox"></td><td>Text 2</td></tr>
<tr><td><input type="checkbox"></td><td>Text 3</td></tr>
</table>

$(function(){
$('input[type=checkbox]').each(function(){
//this.checked = true;
var strVal = $(this).closest('td').next('td').text();
if (strVal=='Text 2')
this.checked = true;
//alert(strVal);
});
});

Answer

The .filter() method is so concise and straight-forward:

$(function(){
    $(':checkbox').filter(function(){
  	return $(this).closest('tr').find('td').last().text() == 'Text 2';
    })
    .prop('checked',true);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<table id="table1">
<tr><td><input type="checkbox"></td><td>Text 1</td></tr>
<tr><td><input type="checkbox"></td><td>Text 2</td></tr>
<tr><td><input type="checkbox"></td><td>Text 3</td></tr>
<tr><td><input type="checkbox"></td><td>Text 2</td></tr>
</table>