Не работает переключатель у `checkbox`
Не работает переключатель у checkbox. Остается активным только у первого где, в html задан cheked. В чем может быть ошибка?
$(document).ready(function() {
//checkbox
$.each($('.checkbox'), function() {
if ($(this).find('input').prop('checked') == true) {
$(this).addClass('active');
}
});
$(document).on('click', 'checkbox', function() {
if ($(this).hasClass('active')) {
$(this).find('input').prop('checked', false);
} else {
$(this).find('input').prop('checked', true);
}
$(this).toggleClass('active');
return false;
});
});
<body>
<div class="wrapper">
<form action="#" class="block-form">
<div class="block-form__title">Form style</div>
<div class="block-form__input">
<div class="checkbox">
Первый выключючатель
<input type="checkbox" checked name="namechekbox_1">
</div>
<div class="checkbox">
Второй выключючатель
<input type="checkbox" name="namechekbox_2">
</div>
</div>
<div class="block-form__input">
<div class="radiobittons">
<div class="radiobuttons__item">
Вариант 1
<input type="radio" value="1" name="nameradio">
</div>
<div class="radiobuttons__item">
Вариант 2
<input type="radio" value="2" name="nameradio">
</div>
<div class="radiobuttons__item">
Вариант 3
<input type="radio" value="3" name="nameradio">
</div>
</div>
</div>
<button type="submit" class="button">Отправить форму</button>
</form>
</div>
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
<script src="js/script.js"></script>
</body>
Ответы (1 шт):
Автор решения: Vladimir
→ Ссылка
Вот самое простое решение, взятое отсюда
Конечно же вам нужно его кастомизировать под свою задачу
.switch {
position: relative;
display: inline-block;
width: 60px;
height: 34px;
}
.switch input {
opacity: 0;
width: 0;
height: 0;
}
.slider {
position: absolute;
cursor: pointer;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: #ccc;
-webkit-transition: .4s;
transition: .4s;
}
.slider:before {
position: absolute;
content: "";
height: 26px;
width: 26px;
left: 4px;
bottom: 4px;
background-color: white;
-webkit-transition: .4s;
transition: .4s;
}
input:checked + .slider {
background-color: #2196F3;
}
input:focus + .slider {
box-shadow: 0 0 1px #2196F3;
}
input:checked + .slider:before {
-webkit-transform: translateX(26px);
-ms-transform: translateX(26px);
transform: translateX(26px);
}
/* Rounded sliders */
.slider.round {
border-radius: 34px;
}
.slider.round:before {
border-radius: 50%;
}
<label class="switch">
<input type="checkbox">
<span class="slider round"></span>
</label>
<label class="switch">
<input type="checkbox" checked>
<span class="slider round"></span>
</label>