5

Hello I am building a form with 1 checkbox. The rest of the form fields work fine but whether the checkbox is checked or not the value is always 'on'.

My code:

<input  id="checkbox_<?=$row['csid'];?>" type="checkbox" <?php if($row['feedbackVisible'] == 'yes') { echo "checked='true'";}?> >

and how i get value with jQuery:

var review_visible_website = $('#checkbox_'+ modalId).val();

The checkbox starts checked but if i uncheck it, it still gives me value 'on'. What am I doing wrong?

Charlie
  • 22,886
  • 11
  • 59
  • 90
BRG
  • 380
  • 6
  • 24

2 Answers2

8

Here are few ways you can test a check box with JQuery

// First method - Recommended
$('#checkbox').prop('checked')  // Boolean true

// Second method - Makes code more readable (e.g. in if statements)
$('#checkbox').is(':checked')  // Boolean true

// Third method - Selecting the checkbox & filtering by :checked selector
$('#checkbox:checked').length  // Integer >0
$('#checkbox:checked').size()  // .size() can be used instead of .length

// Fourth method - Getting DOM object reference
$('#checkbox').get(0).checked  // Boolean true
$('#checkbox')[0].checked      // Boolean true (same as above)
Charlie
  • 22,886
  • 11
  • 59
  • 90
  • 1
    first method is the best! my problem was that i was checking the value with `.val` so it was always the value, no matter if checked or not. Thank you Charlie! – Barbz_YHOOL Jul 15 '20 at 22:54
3

Another way using javascript you can do like this:

    if( document.getElementById('checkbox').checked == true ){
        // checked
    }
    else{
        // not checked
    }
Vijay Dohare
  • 731
  • 5
  • 22
HarisH Sharma
  • 1,101
  • 1
  • 11
  • 38