checking to see if Checkbox is checked is being skipped during execution

96 views Asked by At

I've been racking my brain around this for hours and haven't gotten anywhere. I have a simple form that I will be submitting to a database, after validation and vetting of course.

However, I'm hung up with retrieving the state of the checkbox that I am using. My Code returns all values except for the checkbox and is almost like it is skipping the retrieval of the Checkbox state because the alerts after the variable declaration because the alerts with the other values fire and show.

However the checked property isn't returning anything. I've searched and found countless ways of doing this and I felt like I have tried all of them. Below is just a few ways I've tried. Can anyone see what I am doing wrong???

$(function() {
  $('#submit').on('click', function() {
    var studId = $('input[name="Selected"]:checked').val();
    var classId = $('#ClassSelection').find(":selected").val();
    var classCode = $('input[name="Code"]').val();
    //var isOnline=$("input[type='checkbox']").val();
    //var isOnline=$("input[name='isOnline']").prop('checked');
    //var isOnline=$("input[name='isOnline']").is('checked');
    var isOnline = $("input[name='isOnline']").val();
    alert(studId);
    alert(classId);
    alert(classCode);
    alert(isOnline);
  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" name="isOnline" class="form-control">
<input type="button" class="btn btn-primary" id="submit" value="Submit">

2

There are 2 answers

0
Raining_Crumbs On BEST ANSWER

It appears that my Wamp server was acting up and wasn't displaying my latest pushes to the site. This explains why it seemed like it was skipping my code without breaking. I restarted my wamp server and it started recognizing my changes.

1
delpielo On

As Tyler Roper pointed out, .prop() function should just work.

You can try

$('#submit').on('click', function() {
    var isOnline1=$("input[type='checkbox']").val();
    var isOnline2=$("input[name='isOnline']").prop('checked');
    var isOnline3=$("input[name='isOnline']").is('checked');
    console.log(isOnline1);
    console.log(isOnline2);
    console.log(isOnline3);
});

I created a codepen for it: https://codepen.io/delpielo/pen/zJmevg, simply comparing the output when you click on 'submit' button with the checkbox checked / unchecked.

  • .val() always return 'on' - not what you want
  • .is('checked') always return false - not what you want
  • .prop('checked') - returns false if not checked, true otherwise, exactly what you are looking for