2012-08-09 72 views
-1

我使用這個代碼驗證使用AJAX和jQuery表單輸入字段....在此頁面:http://www.kbay.in/ajaxform/index.phpPHP複選框驗證碼ammendment

$(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()); 

但我有添加一個複選框,但不知道如何驗證它使用此腳本...任何想法....?

回答

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); 
+0

似乎工作的程度......但不完全...謝謝...做我有改變這個 '+'&comment ='+ encodeURIComponent(comment.val());' to this '+'&comment ='+ encodeURIComponent(!commentChecked);' – 2012-08-09 10:15:47

+0

您無需通過檢查,請參閱添加的代碼 – 2012-08-09 10:24:11

1

添加一個複選框,你的HTML ...東西像這樣:

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

和jQuery代碼,以檢查其是否已選中或不應該是這樣的:

if ($("#ch1").prop("checked")) { 
    alert("is checked"); 
} 
else { 
    alert("is not checked"); 
}