CloudyKooper
CloudyKooper

Reputation: 717

How can I check to see if my checkboxes are checked?

I have a list of checkboxes that I would like to monitor. They are loaded on the form something like this:

In the Java script the conditional compilation is turned off and I have a syntax error. Can someone please show me how to go about this the right or maybe point me to a tutorial that may help?

Thanks.

So I put the JQuery function inside a working foreach loop to check the checked status of each checkbox but the alert says checked each even for those that are not checked. What am I doing wrong here?

foreach (var course in courses.Select((x, i) => new { Data = x, Index = i }))
{
    <script type="text/javascript">
       $(document).ready(function () {
          $('#saveBtn').click(function () {
              if ($('#checkbox').is(':checked')) {
                     alert('checked');
              }
              else
                 alert('unchecked');
         });
       });
   </script>
}

Upvotes: 0

Views: 359

Answers (2)

Manish Mishra
Manish Mishra

Reputation: 12375

you can find you whether any checkbox is checked or not in javascript by getting its checked status as below:

<script language="javascript" type="text/javascript">
    var checkStatus = document.getElementById("checkBoxId").checked;
    alert(checkStatus);
</script>

through jQuery you can do like this:

    if($('#checkBoxId').is(':checked') ){
     //your logic
    }

you can trap change event of checkbox like this:

 $('input:checkbox').change(function(){ 
    if($(this).is(':checked')){
        alert('checked');
    }
    else
        alert('unchecked');
});

see this fiddle

Upvotes: 0

Sharun
Sharun

Reputation: 3082

You can traverse the checkboxes in you page and store the values of checked ones in an array like this:

<script type="text/javascript">
  $(document).ready(function () {

var selected = new Array();
$("input:checkbox:checked").each(function()
{
    selected.push($(this).val());
});

});

   </script>

Upvotes: 1

Related Questions