Select a link, will automatically check the box to the left of it

I want the user to be able to move the mouse cursor over the link, click it, and it will automatically check the box to the left of it, and when they select it, clear the box.

How to do it?

<input type="checkbox" name="favorite_color" value="Orange"> <a href="#" rel="favorite_color">Orange</a>

+3
source share
4 answers

Instead of a link (anchor), use <label>one that is designed for this:

<input type="checkbox" name="favorite_color" id="favorite_color" value="Orange"> 
<label for="favorite_color">Orange</label>

Or without id, wrapped around him:

<label><input type="checkbox" name="favorite_color" value="Orange"> Orange</label>

Both of them do not require JavaScript, just the built-in behavior of the browser.

+9
source
$('a').click(function() {
  var checkbox = $(this).prev('input[type="checkbox"]')
  checkbox.attr('checked', checkbox.is(':checked'));
}
+3
source
<input type="checkbox" id="chk" name="favorite_color" value="Orange">
<a href="#" rel="favorite_color" onclick="document.getElementById('chk').checked = true;"> Orange</a>
+1

? / .

<label>
    <input type="checkbox" name="favorite_color" value="Orange">
    <span class="make_it_look_like_a_link">Orange</span>
</label>
+1

Source: https://habr.com/ru/post/1778181/


All Articles