[英]Jquery keep track of checkboxes changes
所以,我有几个复选框,根据选择的数量,我需要在屏幕上显示一条消息:
<div class="container">
<h2>Pick you toppings (3 max):</h2>
<input type="checkbox" name="one" id="one"> Option 1<br>
<input type="checkbox" name="two" id="two"> Option 2<br>
<input type="checkbox" name="three" id="three"> Option 3<br>
<input type="checkbox" name="four" id="four"> Option 4<br>
<input type="checkbox" name="five" id="five"> Option 5<br>
</div>
<div class="submited">
<button id="submit">Submit!</button>
<p></p>
</div>
jquery 的想法是,当没有选中复选框时,一条消息应该显示(在<p>
之间)我们需要选择至少 1 个。我们最多可以选择 3 个选项,而选项 4 和 5 不能同时被采摘。
一旦我们按下提交,就会弹出一个警告,显示错误(如果是这种情况)或成功(如果上述情况均未发生)。
我似乎无法让 javascript 部分工作。
这是我到目前为止:
$(":checkbox").change(function() {
if($(":checkbox:checked").length > 3){
$('p').html("You can not pick more than 3")
} else if ($(":checkbox:checked").length < 1){
$('p').html("Pick at least 1")
} else if ($('#four').is(':checked') && $('#five').is(':checked')){
$('p').html("Can not pick those 2")
} else{
$('p').html("hmmm")
}
});
<h2>Pick you toppings (3 max):</h2>
<input type="checkbox" name="one" id="one"> Option 1<br>
<input type="checkbox" name="two" id="two"> Option 2<br>
<input type="checkbox" name="three" id="three"> Option 3<br>
<input type="checkbox" name="four" id="four"> Option 4<br>
<input type="checkbox" name="five" id="five"> Option 5<br>
</div>
<div class="submited">
<button id="submit" onclick="check()">Submit!</button>
<p></p>
</div>
<script>
function check(){
if($(":checkbox:checked").length > 3){
alert("too much box checked.");
} else if ($(":checkbox:checked").length < 1){
alert("not enought box check.")
} else if ($('#four').is(':checked') && $('#five').is(':checked')){
alert("can't choose the five and the fourth box in the same time.")
} else{
alert("Works!")
}
}
</script>
你的代码看起来不错,但如果你想要一个弹出窗口之类的警报,你可以使用它。 如果此答案对您没有帮助,您能否进一步解释您想要的内容,请
$(document).ready(function(){
$("#submit").click(function(){
var len = $("input[type='checkbox']:checked").length;
if(len > 3){
$("p").html("Select a max of 3");
}
else if (len == 0){
$("p").html("Select at least one");
}
});
});
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.