Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery click check nearest checkbox

I'm trying to use a link to check a checkbox with jQuery. My HTML is:

<table>
  <tr>
    <td><input type="checkbox" value="test" /></td>
    <td><a class="editbutton" href="#">edit</a></td>
  </tr>
</table>

I have been playing with this jquery:

jQuery('.editbutton').click(function($) {
    jQuery(this).closest('[type=checkbox]').attr('checked', true);
});

Unfortunately this isn't working. Any ideas?

like image 589
David Brooks Avatar asked Dec 15 '22 03:12

David Brooks


1 Answers

Use .prop() instead of .attr(), Because .prop is made for setting the properties. By the way your selector is wrong. .closest() will traverse up the dom tree.

Please read the following for more reference : .prop() .closest()

Try this,

jQuery('.editbutton').click(function($) {
    jQuery(this).closest('td').prev().find('[type=checkbox]').prop('checked', true);
});

Or as @kappa suggested.

jQuery('.editbutton').click(function($) {
    jQuery(this).closest('tr').find('[type=checkbox]').prop('checked', true);
});

DEMO

like image 159
Rajaprabhu Aravindasamy Avatar answered Dec 17 '22 15:12

Rajaprabhu Aravindasamy