Как получить значение флажка checked bootstrap

#html #jquery

#HTML #jquery

Вопрос:

Я создал эту HTML-форму:

 <div class="animated-switch">
  <input id="switch-success" name="switch-success" checked="" type="checkbox">
  <label for="switch-success" class="label-success"></label>
</div>  
  

Как мне узнать, проверен ли ввод или нет?

Я попробовал следующее, но ничего не предупредил:

 $(document).on('click','.animated-switch',function(e){
    alert($('#switch-success:checked').val() );
});
  

Вот файл JSFIDDLE, чтобы увидеть мой наглядный пример:https://jsfiddle.net/s2f9q3fv /

Комментарии:

1. Попробуйте if ($('#switch-success').is(':checked')) { alert('Checked.'); }

Ответ №1:

Вы можете просто использовать функцию $(this) и find для поиска input в этом div, чтобы проверить, есть ли это checked или нет.

Живая демонстрация:

 $(document).on('change', '.animated-switch', function(e) {
  if ($(this).find('input').is(':checked')) {
    console.log('Checked')
  } else {
    console.log('Not Checked')
  }
});  
 .animated-switch>input[type="checkbox"] {
  display: none;
}

.animated-switch>label {
  cursor: pointer;
  height: 0px;
  position: relative;
  width: 40px;
}

.animated-switch>label::before {
  background: black;
  box-shadow: inset 0px 0px 10px rgba(0, 0, 0, 0.5);
  border-radius: 8px;
  content: '';
  height: 16px;
  margin-top: -8px;
  position: absolute;
  opacity: 0.3;
  transition: all 0.4s ease-in-out;
  width: 40px;
}

.animated-switch>label::after {
  background: white;
  border-radius: 16px;
  box-shadow: 0px 0px 5px rgba(0, 0, 0, 0.3);
  content: '';
  height: 24px;
  left: -4px;
  margin-top: -8px;
  position: absolute;
  top: -4px;
  transition: all 0.3s ease-in-out;
  width: 24px;
}

.animated-switch>input[type="checkbox"]:checked label::before {
  background: inherit;
  opacity: 0.5;
}

.animated-switch>input[type="checkbox"]:checked label::after {
  background: inherit;
  left: 20px;
}  
 <!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<div class="animated-switch">
  <input id="switch-success" name="switch-success" checked="" value="test" type="checkbox">
  <label for="switch-success" class="label-success"></label>
</div>