Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check only checkboxes with a specific value

Tags:

jquery

I am trying to check only checkboxes that have a specific value. I know how to get the value and I know how to check all checkboxes but I cannot figure out how to check only the ones with, lets say value of '200'

My example code:

<tr>
    <td><input class="chk_box" type="checkbox" value="200" /></td>
    <td class="code">200</td>
</tr>
<tr>
    <td><input class="chk_box" type="checkbox" value="0" /></td>
    <td class="code">0</td>
</tr>
<tr>
    <td><input class="chk_box" type="checkbox" value="0" /></td>
    <td class="code">0</td>
</tr>
<tr>
    <td><input class="chk_box" type="checkbox" value="200" /></td>
    <td class="code">200</td>
</tr>
<tr>
    <td><input class="chk_box" type="checkbox" value="300" /></td>
    <td class="code">300</td>
</tr>

<input type="checkbox" class="checkbox_200" label="check 200"  />check 200

So now I need jQuery code to complete my code. I appreciate any help.

BTW. Is there a way to check '200' and '300' in one go?

UPDATED!

like image 565
Chriser Avatar asked Dec 15 '22 12:12

Chriser


2 Answers

Your checkboxes do not have value attributes, if you want to check the checkboxes according to the text content of the TD elements, you can use filter method.

$('td.code').filter(function(){
   var txt = this.textContent || this.innerText;
   return txt === '200' || txt === '300';  
}).prev().find('input').prop('checked', true);

Update:

$('tr input[type=checkbox][value=200]').prop('checked', true);

Alternative:

$('tr input[type=checkbox]').filter(function(){
   return this.value === '200' || this.value === '300';
}).prop('checked', true);
like image 50
undefined Avatar answered Jan 11 '23 09:01

undefined


Your checkboxes has not value. There is only text next ty its. Try to change code and set value for inputs.

<input class="chk_box" type="checkbox" value="200" /> 200
<br />
<input class="chk_box" type="checkbox" value="0" />0
<br />
<input class="chk_box" type="checkbox" value="0" />0
<br />
<input class="chk_box" type="checkbox" value="200" /> 200
<br />
<input class="chk_box" type="checkbox" value="300" /> 300

The you can use this selector:

input[type=checkbox][value="200"]

For jquery use it inside $("").

Example: http://jsbin.com/oyetit/1/edit

like image 22
Saram Avatar answered Jan 11 '23 08:01

Saram