我使用此代码使用ajax和jquery验证表单输入字段....在此页面上:http://www.kbay.in/ajaxform/index.php
$(document).ready(function() {
//if submit button is clicked
$('#submit').click(function () {
//Get the data from all the fields
var name = $('input[name=name]');
var phone = $('input[name=phone]');
var package_name = $('input[name=package_name]');
var comment = $('input[name=comment]');
//Simple validation to make sure user entered something
//If error found, add hightlight class to the text field
if (name.val()=='') {
name.addClass('hightlight');
return false;
} else name.removeClass('hightlight');
if (phone.val()=='') {
phone.addClass('hightlight');
return false;
} else phone.removeClass('hightlight');
if (package_name.val()=='') {
package_name.addClass('hightlight');
return false;
} else package_name.removeClass('hightlight');
if (comment.val()=='') {
comment.addClass('hightlight');
return false;
} else comment.removeClass('hightlight');
//organize the data properly
var data = 'name=' + name.val() + '&phone=' + phone.val() + '&package_name=' +
package_name.val() + '&comment=' + encodeURIComponent(comment.val());
但我添加了一个复选框,但不知道如何使用此脚本验证它...任何想法......?
答案 0 :(得分:2)
您可以使用是(“:已选中”):
var commentChecked = $("input[name='comment']").is(':checked'); //returns true or false
var commentVal; //define variable for storing comment value
和
if (!commentChecked) {
commentVal = "";
comment.addClass('hightlight');
return false;
} else {
comment.removeClass('hightlight');
commentVal = comment.val();;
}
和
var data = 'name=' + name.val() + '&phone=' + phone.val() + '&package_name=' +
package_name.val() + '&comment=' + encodeURIComponent(commentVal);
答案 1 :(得分:1)
在HTML中添加一个复选框......如下所示:
<input type="checkbox" id="ch1">
以及用于检查是否已检查的jQuery代码应如下所示:
if ($("#ch1").prop("checked")) {
alert("is checked");
}
else {
alert("is not checked");
}