0

С одной задачкой появилась небольшая проблема. Нужно что бы после выделения checkbox и нажатия кнопки выводилось id этого checkbox, но у меня чего то не выходит, помогите пожалуйста.

$('#button_').click(function() {
            if ($(':checkbox').is(':checked')) {
            var id = this.id;//здесь должно сохранятся id checkbox
            alert(id);
          }
          else {
            alert('Перед нажатием на кнопку выделите checkbox!');
          }
        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title></title>
    <script src="jquery.min.js"></script>
    <script src="script.js"></script>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
  <input type="checkbox" id="1">
    <input type="checkbox" id="2">
    <input type="checkbox" id="3">
    <br>
    <input type="button" id="button_" value="Tap me!">
  </body>
</html>

2 ответа 2

2

$('#button_').click(function() {
  var msg = $('input[type=checkbox]:checked').attr('id') || 'Перед нажатием на кнопку выделите checkbox!';
  alert(msg);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<input type="checkbox" id="1">
<input type="checkbox" id="2">
<input type="checkbox" id="3">
<br>
<input type="button" id="button_" value="Tap me!">

0
2

для этой задачи совсем не нужно подключать громоздкий jquery

document.getElementById('button_').onclick=function(){

  var chkd=document.querySelectorAll('input:checked');
  for (var i=0; i<chkd.length; i++){
   console.log(chkd[i].getAttribute("id"));
                                    }
  chkd.length==0 ? console.log('Перед нажатием на кнопку выделите checkbox!'):0;
        
}
    <input type="checkbox" id="1">
    <input type="checkbox" id="2">
    <input type="checkbox" id="3">
    <br>
    <input type="button" id="button_" value="Tap me!">

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.