4

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?

David Brooks
  • 759
  • 2
  • 15
  • 29
  • 8
    Have you ever heard about HTML Labels? They do this without any JavaScript. – epascarello Dec 10 '13 at 17:04
  • @epascarello Post it as answer, I would certainly upvote. – kapa Dec 10 '13 at 17:12
  • [`.closest()`](http://api.jquery.com/closest/) looks for the closest ancestor element. You need to do a little more [tree traversal](http://api.jquery.com/category/traversing/tree-traversal/). – Blazemonger Dec 10 '13 at 17:17
  • @epascarello I have no control over the checkbox or much on the HTML in general, hence the jQuery! – David Brooks Dec 10 '13 at 18:15

1 Answers1

12

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

Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130
  • 1
    If you simply look for the closest tr, you do not need that `prev`. – kapa Dec 10 '13 at 17:14
  • @kappa I just thought that, hooking up `tr` will need more traversals. Am I thinking right.? Please clarify. – Rajaprabhu Aravindasamy Dec 10 '13 at 17:15
  • Sounds like microoptimization to me. Relying on prev is quite vulnerable - you might add another cell between the two later. I don't say your solution is wrong, just added an alternative. – kapa Dec 10 '13 at 17:18
  • 1
    @quite `vulnerable for future modifications`. Great point. Thank you. Updated accordingly. – Rajaprabhu Aravindasamy Dec 10 '13 at 17:20
  • +1, excellent answer, i hope you implement a [toggle check](https://stackoverflow.com/a/4177175/7735285) function. that's the point of checkbox. – wpcoder Nov 07 '17 at 14:45