Я пытаюсь условно добавить класс «закрытый-3» ко всем дочерним «входным» элементам предка. Предок должен содержать классы ".summon-next-element.on-sub-sub-level". Однако я не получаю никакого эффекта - ни класс не добавлен, ни ошибка в консоли, ничего. Вот jQuery:
$('.summon-next-element.on-sub-sub-level').each(function() {
if ($(this).find("input").is(":checked")) {
$(this).nextAll(".summoned-element").first().find("input").addClass("opened-3").removeClass("closed-3");
} else {
$(this).nextAll(".summoned-element").first().find("input").addClass("closed-3").removeClass("opened-3");
}
});
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class = "summon-next-element on-sub-sub-level">
<input type = "radio" name = "frais_renovation" id = "frais_renovation_oui" class = "oui">
<label for = "frais_renovation_oui">oui</label>
</div>
<div class = "checkbox">
<input type = "radio" name = "frais_renovation" id = "frais_renovation_non" class = "non">
<label for = "frais_renovation_non">non</label>
</div>
<div class = "summoned-element">
<div class = "checkbox info-circle right">
<input type = "radio" name = "frais_renovation_justificatifs" id = "frais_renovation_fichier">
<label for = "frais_renovation_fichier">
Mes justificatifs 1
</label>
</div>
<div class = "checkbox info-circle right">
<input type = "radio" name = "frais_renovation_justificatifs" id = "frais_renovation_tickets" checked>
<label for = "frais_renovation_tickets">
Mes justificatifs 2
</label>
</div>
</div>
<!-- end of summoned element -->
Большое вам спасибо за вашу помощь!
Если вход не проверен, он должен удалить класс «open-3», но вместо этого должен добавить класс «closed-3». Тоже не идет....
вам нужно дополнительно обернуть код в проверяемое событие для переключателей
@sergeykuznetsov, да, похоже, проблема с переключателями, так как они отлично работают с флажками. Как обернуть код в проверенное событие? извини...
@BenViatte, я дал тебе решение. Проверьте, пожалуйста.
@BenViatte, хотели получить такой результат?
Большое вам спасибо, благодаря вашей помощи и другим здесь, я наконец установил рабочую версию. Большая благодарность.
Проблема в том, что вы не зацикливаете каждый из входов, поэтому, когда вы проверяете, отмечен ли вход, он всегда будет выбирать первый внутри .on-sub-sub-level
.
Попробуйте с:
$('.summon-next-element.on-sub-sub-level ~ .summoned-element input').each(function() {
if ($(this).is(":checked")) {
$(this).addClass("opened-3").removeClass("closed-3");
} else {
$(this).addClass("closed-3").removeClass("opened-3");
}
});
Демо
$('.summon-next-element.on-sub-sub-level ~ .summoned-element input').each(function() {
if ($(this).is(":checked")) {
$(this).addClass("opened-3").removeClass("closed-3");
} else {
$(this).addClass("closed-3").removeClass("opened-3");
}
});
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class = "summon-next-element on-sub-sub-level">
<input type = "radio" name = "frais_renovation" id = "frais_renovation_oui" class = "oui">
<label for = "frais_renovation_oui">oui</label>
</div>
<div class = "checkbox">
<input type = "radio" name = "frais_renovation" id = "frais_renovation_non" class = "non">
<label for = "frais_renovation_non">non</label>
</div>
<div class = "summoned-element">
<div class = "checkbox info-circle right">
<input type = "radio" name = "frais_renovation_justificatifs" id = "frais_renovation_fichier">
<label for = "frais_renovation_fichier">
Mes justificatifs 1
</label>
</div>
<div class = "checkbox info-circle right">
<input type = "radio" name = "frais_renovation_justificatifs" id = "frais_renovation_tickets" checked>
<label for = "frais_renovation_tickets">
Mes justificatifs 2
</label>
</div>
</div>
<!-- end of summoned element -->
Спасибо. Кажется, что это немного дальше, но все равно не добавляются ни открытые, ни закрытые классы....
$("selector1").is("selector2")
истинно, если любой из элементов, выбранных selector1
, удовлетворяет selector2
, а не только первый.
@BenViatte Я не понимаю вас, если вы запустите демо и проверите входы, вы увидите, что к ним добавляются закрытые или открытые
Вы правы, похоже, это работает на фрагменте кода, но по какой-то причине на моем сайте это не работает... просто чтобы все усложнить...
Также необходимо завернуть свою логику в событие выбора радиокнопки, по которому будет происходить сокращенное присвоение/удаление классов:
$(this).on('click', function() { ... }
В вашем коде также была неправильная ссылка на класс.
$('div').find('input[type=radio]').each(function() {
$(this).on('click', function() {
$('input[type=radio]').addClass("closed-3").removeClass("opened-3");
if ($(this).is(":checked")) {
$(this).addClass("opened-3").removeClass("closed-3");
}
});
});
<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class = "summon-next-element on-sub-sub-level">
<input type = "radio" name = "frais_renovation" id = "frais_renovation_oui" class = "oui">
<label for = "frais_renovation_oui">oui</label>
</div>
<div class = "checkbox">
<input type = "radio" name = "frais_renovation" id = "frais_renovation_non" class = "non">
<label for = "frais_renovation_non">non</label>
</div>
<div class = "summoned-element">
<div class = "checkbox info-circle right">
<input type = "radio" name = "frais_renovation_justificatifs" id = "frais_renovation_fichier">
<label for = "frais_renovation_fichier">
Mes justificatifs 1
</label>
</div>
<div class = "checkbox info-circle right">
<input type = "radio" name = "frais_renovation_justificatifs" id = "frais_renovation_tickets" checked>
<label for = "frais_renovation_tickets">
Mes justificatifs 2
</label>
</div>
</div>
<!-- end of summoned element -->
Ни один из входов в
.summon-next-element.on-sub-level
не проверяется. Таким образом, он удалит класс, а не добавит его.