这是复选框的HTML,我有一个只允许选择三个的功能
<form class="interestSearchCriteria">
<input type="checkbox" name="walking" value="Walking"> Walking
<input type="checkbox" name="running" value="Running" > Running
<input type="checkbox" name="hiking" value="Hiking" > Hiking
<input type="checkbox" name="surfing" value="Surfing" > Surfing
<input type="checkbox" name="powerkiting" value="Kiting" > Kiting
<input type="checkbox" name="gym" value="GYM" > GYM
<input type="checkbox" name="cycling" value="Cycling" > Cycling<br><br><br>
<input type="submit" value="Submit" id="updateInterest">
</form>
Ajax调用,我有三个变量但是如何为每个单独的变量分配第一个,第二个和第三个标记值,以便我可以将帖子发送到三个单独的列?
$(document).ready(function() {
$(document).on('click', '#updateInterest', function() {
var firstInterest = $('input[type=checkbox]:checked').val();
var secondInterest=$('input[type=checkbox]:checked').val();
var thirdInterest=$('input[type=checkbox]:checked').val();
$.ajax({
type: "POST",
url: "http://localhost:8888/link",
data: {
option1: firstInterest,
option2:secondInterest,
option3:thirdInterest
}
});
})
})
答案 0 :(得分:0)
$(document).on('click', '#updateInterest', function() {
var checked = $('input[type=checkbox]:checked');
var firstInterest = checked.eq(0).val();
var secondInterest = checked.length > 1 ? checked.eq(1).val() : "";
var thirdInterest = checked.length > 2 ? checked.eq(2).val() : "";
console.log(firstInterest);
console.log(secondInterest);
console.log(thirdInterest);
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="interestSearchCriteria">
<input type="checkbox" name="walking" value="Walking"> Walking
<input type="checkbox" name="running" value="Running"> Running
<input type="checkbox" name="hiking" value="Hiking"> Hiking
<input type="checkbox" name="surfing" value="Surfing"> Surfing
<input type="checkbox" name="powerkiting" value="Kiting"> Kiting
<input type="checkbox" name="gym" value="GYM"> GYM
<input type="checkbox" name="cycling" value="Cycling"> Cycling<br><br><br>
<input type="submit" value="Submit" id="updateInterest">
</form>
选中所有选中的复选框:
$('input[type=checkbox]:checked')
获得第一,第二,第三或任何其他指数(比如n):
.eq(n)
答案 1 :(得分:0)
这将允许选择最多3个选项,并将数据放入ajax调用的正确选项字段中。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
$(document).ready(function() {
$(document).on('click', '#updateInterest', function(e) {
e.preventDefault(); //stop default postback behaviour
var valid = true;
var data = { option1 : null, option2 : null, option3 : null };
$("input[type=checkbox]:checked").each(function(i, obj) {
if (i < 3) {
data["option" + (i+1).toString()] = this.value;
}
else {
alert("Please select up to 3 items");
valid = false;
return;
}
});
if (valid == false) { return; }
alert(JSON.stringify(data)); //just to test
$.ajax({
type: "POST",
url: "http://localhost:8888/link",
data: data
});
});
})