Javascript-форум (https://javascript.ru/forum/)
-   Элементы интерфейса (https://javascript.ru/forum/dom-window/)
-   -   Checkbox и ссылка (https://javascript.ru/forum/dom-window/56804-checkbox-i-ssylka.html)

vasyakrn 05.07.2015 01:35

Checkbox и ссылка
 
Помогите написать js код чтоб при клике на ссылку отмечался чекбокс. Брать все в тег <label> не вариант, так как не работает в некоторих браузерах. Вот мой код

<input id="one" type="checkbox" />
<a id="one"  >Один</a>

<input id="two" type="checkbox" />
<a id="two"  >Два</a>

<input id="three" type="checkbox" />
<a id="three"  >Три</a>

Decode 05.07.2015 03:27

<!doctype html>
<html>
<head>
  <meta charset="utf-8" />
  <title></title>
</head>
<body>
  <div class="block">
    <input id="one" type="checkbox" />
    <a href="#" id="one">Один</a>

    <input id="two" type="checkbox" />
    <a href="#" id="two">Два</a>

    <input id="three" type="checkbox" />
    <a href="#" id="three">Три</a>
  </div>


  <script>
    document.querySelector('.block').onclick = function(e) {
      e.preventDefault();

      var target, id, elem;

      target = e.target;
      if(target.nodeName != 'A') return;

      id = target.getAttribute('id');
      if(!id) return;

      elem = document.getElementById(id);
      elem.checked = (elem.checked) ? false : true;
    };
  </script>

</body>
</html>

рони 05.07.2015 11:43

Decode,
как вариант
elem = target.previousElementSibling;
      elem.checked = !elem.checked;


Часовой пояс GMT +3, время: 16:12.