我在codeLAB上找到了这个代码,而且我只是想在" Cricket"和#34;拳击"检查。目前,如果选中这两个选项,它们都会工作,但是当选中其他选项时也是如此。
https://jsfiddle.net/kubus1234/oksm8eaw/
$("button").click(function() {
var favorite = [];
$.each($("input[name='sport']:checked"), function() {
favorite.push($(this).val());
});
var test = [];
$.each($("input[name='sport']:checked"), function() {
test.push($(this).val());
});
if (favorite[1] == "cricket" || test[1] == "boxing") {
alert("Your are the best");
} else {
alert("Your are looser");
}
});
任何解决方案?
答案 0 :(得分:0)
这很容易研究,但无论如何我都会发布一个解决方案
1)我给了复选框ids
2)我更改了JavaScript以检查是否同时使用.is(":checked")
<form>
<h3>Select your favorite sports:</h3>
<label><input type="checkbox" id="chkFootball" value="football" name="sport"> Football</label>
<label><input type="checkbox" id="chkBaseball" value="baseball" name="sport"> Baseball</label>
<label><input type="checkbox" id="chkCricket" value="cricket" name="sport"> Cricket</label>
<label><input type="checkbox" id="chkBoxing" value="boxing" name="sport"> Boxing</label>
<label><input type="checkbox" id="chkRacing" value="racing" name="sport"> Racing</label>
<label><input type="checkbox" id="chkSwimming" value="swimming" name="sport"> Swimming</label>
<br>
<button type="button">Get Values</button>
</form>
$(document).ready(function() {
$("button").click(function(){
if ($('#chkCricket').is(':checked') && $('#chkBoxing').is(':checked')) {
alert("Checked");
}
else {
alert("Not checked");
}
});
});
答案 1 :(得分:0)
不确定您为何选择了两次选中的复选框,但这是获得结果的一种方法:
urlString
$(document).ready(function() {
$("button").click(function() {
var selected = $("input[name='sport']:checked").toArray().map(function(checkbox) {
return $(checkbox).val();
});
if (selected.length === 2 && selected[0] === "cricket" && selected[1] === "boxing") {
alert("You are the best");
} else {
alert("You lose");
}
});
});
答案 2 :(得分:0)
https://jsfiddle.net/oksm8eaw/2/
请不要使用javascript警报。警报导致癌症......
...而是使用id和jQuery html()
:将其添加到HTML:<div id="result"></div>
$(document).ready(function() {
$("button").click(function(){
var matchCount = 0;
$('input').each(function(){
if( this.value == "cricket" || this.value == "boxing") {
if(this.checked) matchCount++;
}
});
if(matchCount>1){
$("#result").html("YUP!");
} else {
$("#result").html("NOPE!");
}
});
});