Determine if checkbox is checked or not in asp.net and javascript

I have a CheckBox control in an asp: Panel as shown below:

<asp:Panel ID="chk" runat="server" Visible="false" CssClass="checkbox checkbox-primary checkbox-single">
    <asp:CheckBox runat="server" ID="valCheck" />
</asp:Panel>

      

I need to check if this CheckBox is checked or not, then I would send 0 or 1 to the function that will do a few more things and when it returns based on the value, if it is greater than 0 it will display the checked checkbox. I need to use this value because I also have some other types of inputs that I set their value based on the value returned from another call.

var checking = false;
function saveCheckBoxData(obj, id, inputType) {
    if (checking) return;
    checking = true;
    var date = $("#MainContent_date").val();
    var column = $(obj).attr("column");
    var dataFieldId = $(obj).attr("dataFieldId ");
    var shift = $(obj).attr("shift");
    var val = 0;
    //if ($("#valCheck").is(':checked')) {
    //    val = 1;
    //}
    //if ($('#valCheck').prop('checked')) {
    //    val = 1;
    //}
    //if ($('#valCheck').attr("checked")) {
    //    val = 1;
    //}
    SaveInput(dataFieldId , shift, inputType, date, column, id, val);
}

      

When I call the SaveInput function, I need to either go through 0 (if the checkbox is not checked) or 1 (if it is checked). The lines I commented out didn't work!

Any feedback would be greatly appreciated!

+3


source to share


2 answers


Id is not exactly valCheck

when used runat="server"

changes element id (check element to see new id) then you need to use jquery selector like:

$("select[id*='valCheck']")

      

or

$("select[id$='valCheck']")

      



or you can just add attr ClientIdMode="Static"

to your asp element.

<asp:CheckBox runat="server" ID="valCheck" ClientIdMode="Static" />

      

If you want to understand why this is happening, take a look at article .

+3


source


In plain javascript

 var isChecked= document.getElementById("myCheck").checked;

      



isChecked

will be true

if checked, and false

if unchecked

0


source







All Articles