select link, automatically checks the checkbox to the left of it
I want to a user to be able to hover over a link, click it, and it will automatically check the checkbox to the left of it, and when they select it, it will uncheck the box.
How do I do this?
开发者_StackOverflow中文版<input type="checkbox" name="favorite_color" value="Orange"> <a href="#" rel="favorite_color">Orange</a>
Instead of a link (anchor), use a <label>
which is designed for this:
<input type="checkbox" name="favorite_color" id="favorite_color" value="Orange">
<label for="favorite_color">Orange</label>
Or without the id
, wrapped around it:
<label><input type="checkbox" name="favorite_color" value="Orange"> Orange</label>
With both of these there's no JavaScript required, just built-in browser behavior.
$('a').click(function() {
var checkbox = $(this).prev('input[type="checkbox"]')
checkbox.attr('checked', checkbox.is(':checked'));
}
<input type="checkbox" id="chk" name="favorite_color" value="Orange">
<a href="#" rel="favorite_color" onclick="document.getElementById('chk').checked = true;"> Orange</a>
Does it have to be a link? You could just underline/highlight a span inside a label.
<label>
<input type="checkbox" name="favorite_color" value="Orange">
<span class="make_it_look_like_a_link">Orange</span>
</label>
精彩评论