-2

我正在使用此代码使用 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());

但我添加了一个复选框,但不知道如何使用这个脚本来验证它......任何想法......?

4

2 回答 2

2

您可以使用is(":checked")

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);
于 2012-08-09T10:02:11.560 回答
1

在您的 HTML 中添加一个复选框......如下所示:

<input type="checkbox" id="ch1">

并且您的 jQuery 代码来检查它是否被检查应该如下所示:

if ($("#ch1").prop("checked")) {
    alert("is checked");
}
else {
    alert("is not checked");
}
于 2012-08-09T10:20:20.633 回答