我需要在提交之前检查复选框的属性,并在POST之前使用jQuery执行错误消息。
例如,如果没有选中朋友,我会在发送数据之前尝试显示警报。 我的代码:
function send(friends)
{
var data = {};
data['url'] = $('#link').attr('src');
val = [];
$("input[name='friends']").each(function(i)
{
if(this.checked == true)
val.push(this.value);
});
data['friends'] = val;
$.post('send.php', data);
$("#sentmsg").addClass("in").fadeIn().delay(5000).fadeOut();
$("input[name='friends']").removeAttr("checked");
$("#success").show();
}
我不确定将其放入代码中的位置:
else if(this.checked == false)
{
alert("no box ticked!");
}
答案 0 :(得分:0)
这可能是一种更简单的方法来检查是否有人被检查......
var checked = $('input[name="friends"]:checked');
//number of checked boxes
var nr_checked = checked.length;
if (!nr_checked) {
alert("no box ticked!");
} else {
//Do your thing
}
答案 1 :(得分:0)
尝试这样的事情
if(val.length == 0){
alert("no box ticked!");
}
答案 2 :(得分:0)
您可以检查val
变量的长度。但要查找所选项目的值,请使用.map()
function send(friends) {
var data = {};
data['url'] = $('#link').attr('src');
//use .map() to convert the dom reference to an array
var val = $("input[name='friends']:checked").map(function (i) {
return this.value
}).get();
if(!val.length){
alert('friends not selected');
return
}
data['friends'] = val;
$.post('send.php', data);
$("#sentmsg").addClass("in").fadeIn().delay(5000).fadeOut();
$("input[name='friends']").removeAttr("checked");
$("#success").show();
}