我有 2 个按钮和 2 个输入。 “购买”按钮只有在两个输入都被选中时才会触发其默认功能。如果不是,它应该用红色边框标记它们。我在这里做错了什么?
jQuery(function($) {
$('.checkedterms:checked').length == $('.checkedterms').length
$("#upsellyes").click(function(e) {
$(".checkedterms").change(function(){
if (!$('.checkedterms:checked').length == $('.checkedterms').length) {
e.preventDefault();
$("#terms-required").addClass('invalid');
}
else {
$("#terms-required").removeClass('invalid');
}
});
});
});
.invalid {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="terms-required">
<input type="checkbox" class="checkedterms" name="terms" id="terms" style="position: absolute;"><label for="terms" class="checkbox" style="display: inline-block!important;font-weight:normal!important;margin-left: 25px;">I have read <a href="#" >Allgemeinen Geschäftsbedingungen</a>.<span class="required">*</span></label><br />
<input type="checkbox" class="checkedterms" name="terms" id="terms" style="position: absolute;"><label for="terms" class="checkbox" style="display: inline-block!important;font-weight:normal!important;margin-left: 25px;">I have read <a href="#" >Widerrufsbelehrung</a>.<span class="required">*</span></label><br />
</div><br>
<a href="#" id="upsellyes">buy</a><br><br>
<a href="#">no thanks</a>
最佳答案
这里有几个问题:
- 您在代码的开头进行了相等性检查,但什么都不做。
- 您已将
change
处理程序嵌套在按钮的click
处理程序内的复选框上;将其删除。 - 与问题无关,但您使用了重复的
id
属性。它们在 DOM 中必须是唯一的。 - 你的逻辑是倒退的。您声明您希望只有在点击“购买”按钮时未选中两个复选框时才显示红色边框。
您还可以通过缓存复选框选择器和使用 toggleClass()
使逻辑更加简洁。像这样:
jQuery(function($) {
$("#upsellyes").click(function(e) {
var $terms = $('.checkedterms');
$("#terms-required").toggleClass('invalid', $terms.length != $terms.filter(':checked').length);
});
});
.invalid {
border: 1px solid red;
}
.checkedterms {
position: absolute;
}
label {
display: inline-block!important;
font-weight: normal!important;
margin-left: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="terms-required">
<input type="checkbox" class="checkedterms" name="terms" />
<label for="terms" class="checkbox">
I have read <a href="#">Allgemeinen Geschäftsbedingungen</a>.
<span class="required">*</span>
</label><br />
<input type="checkbox" class="checkedterms" name="terms" />
<label for="terms" class="checkbox">
I have read <a href="#" >Widerrufsbelehrung</a>.
<span class="required">*</span>
</label><br />
</div><br />
<a href="#" id="upsellyes">buy</a><br><br>
<a href="#">no thanks</a>
最后请注意单独样式表的使用。内联样式不是一个好主意,应尽可能避免。
关于javascript - 检查是否检查了所有输入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48505755/