I am trying to do a simple function to find the surrounding form, thereafter find all the checkboxes with a specified value and then just check em all 🙂
html
<form action='bla bla bla'>
<a href='javascript:void(0);' onclick='checkAll(2);'>Check all 2s</a>
<input type='checkbox' value='1' /> 1
<input type='checkbox' value='1' /> 1
<input type='checkbox' value='2' /> 2
<input type='checkbox' value='2' /> 2
<input type='checkbox' value='3' /> 3
<input type='checkbox' value='4' /> 3
</form>
js
function checkAll(i) {
var checkboxes = $(this).closest('form').find('input[type=checkbox][value='+i+']');
checkboxes.attr('checked', 'checked');
}
But absolutely nothing happens. What goes wrong? 🙂
The problem is you are using
thisinsidecheckAllwithout a correct initialization. WhencheckAll()is executed,thiswill be bound to to global object (window, in this case).The clicked
<a>element is available throughthisonly to the Javascript code inside theonclickattribute. You have to passthistocheckAll()as a parameter.The HTML code has to be changed like this:
The Javascript code will be: