如何判断是否选中了复选框?

时间:2012-11-05 17:58:24

标签: javascript jquery html forms

我需要能够判断是否选中了复选框以进行一些基本验证。问题:我没有访问PHP生成这个。没有添加类,或者大多数表单都有基本的checked =。定位复选框的最简单方法是什么?

http://www.inpresence.in/event-registration?ee=4

编辑:吓坏了!!这是代码,我只需要定位复选框,其他一切正常。 :check方法的jquery在复选框中使用checked = checked,而不是那里。

   $(document).ready(function(){
    //when the submit button is clicked...
    $("input.btn_event_form_submit").click(function(){

    //find the value of the drop down with one evening or four evenings
    var priceOption = $("#price_option-4").val();

    //match a string ending with "one evening" as the first numbers will be randomly generated by php
    var oneEvening = /^\d{2}\|One Evening$/.test(priceOption);

    //match a string ending with "four evenings" as the first numbers will be randomly generated by php
    var fourEvenings = /^\d{2}\|Four Evenings$/.test(priceOption);

    //HOW DO I GET THE CHECKED BOXES?!
    var checkedBoxCount = $('#dates-1351733097 .valid').is(':checked').length;

    //if one evening is selected make sure the checked boxes count does in fact equal one
    if(oneEvening && checkedBoxCount != 1){
        //if it doesn't alert the user and return false
        alert('You must select one date');
        return false;
    }

    //if one evening isn't selected, four is. make sure the count does indeed in 4
    else if (fourEvenings && checkedBoxCount != 4){
        //if it doesnt alert the user and return to the form
        alert('You must select four dates');
        return false;
    }

    //else, everything checks out!
    else {
        return;
    }

});
});

4 个答案:

答案 0 :(得分:2)

您是否尝试过使用jquery来解决此问题? http://jquery-howto.blogspot.co.uk/2008/12/how-to-check-if-checkbox-is-checked.html

$('#edit-checkbox-id').is(':checked'); 

答案 1 :(得分:2)

使用此JavaScript代码,您可以检查是否选中了复选框:

var isChecked = document.getElementById("my-checkbox").checked;

或者使用jQuery:

var isChecked = $('#my-checkbox').is(':checked');

编辑:试试这个并告诉我它是否有效:

var checkedBoxCount = $('#dates-1351733097 .valid:checked').length;

答案 2 :(得分:0)

使用jquery :checked选择器。 http://api.jquery.com/checked-selector/

答案 3 :(得分:0)

这将为你提供你想要的javascript布尔值:

document.getElementById("Nov.12-4_1").checked

您可以查看来源并查找元素以查看他们拥有的任何ID。

其他答案:OP没有说明他想要一个jquery答案。如果他到目前为止还没有使用jquery做任何事情。我认为仅仅为此添加它会有点过分。