May Sale! All accounts are 40% off this week.

felicia00's avatar

How to check if checkbox is checked?

Is it the correct way to check if the check box is tick?

        <input type="checkbox" class="custom-control-input check" name="A" id="A" value= "<?php if(isset($resDtl[0]) && $resDtl[0]->A==1) echo "checked"; ?>" />
        <label class="custom-control-label" for="A">A</label>

JavaScript

var obj={};

      $(".check").each(function(){
            var name = this.name;
            if ($("[name='" + name + "']:checked").val() == true)
                obj[name] = true;
            else
                obj[name] = "";
        })

        return obj;
0 likes
3 replies
coder222's avatar

For checkbox input the important attributes are:

<input type="checkbox" name="cb_name" value="cb_val" checked="checked" />

When the form is submitted, the value of cb_name will be cb_val whatever its value if the checkbox is checked, if it is not checked then cb_val will not even be set.

Now you can figure out where to put your if(isset(...)) code, instead of in the value attribute it should be outside of it.

<input type="checkbox" name="cb_name" value="1" <?php if ($cb_name == 1) echo 'checked="checked"' ?> />

or if you're using laravel blade template:

<input type="checkbox" name="cb_name" value="1" @if($cb_name == 1) checked="checked" @endif />
1 like
jlrdw's avatar

I usually:

 var mycheck = ($("#yourcheck").prop("checked") == true ? '1' : '0');
1 like
dev_nope's avatar

In vanilla JavaScript you can make use of the checked property of the "checkbox" JavaScript element object. See examples on MDN.

Given you have the following HTML:

<label>
  <input type="checkbox" id="is_admin" name="is_admin" value="1">
  Is Admin
</label>

Then in JavaScript you can do this:

const isAdminCheckbox = document.querySelector('#is_admin');

console.log(isAdminCheckbox.checked ? 'Is Checked' : 'Is Unchecked');

You can check out this codepen example as well 👍

Like @coder222 mentioned, when the checkbox is unchecked and you're POST-ing the form, then that checkbox field won't even be present in PHP's $_POST array. One little trick I like to use to make sure the checkbox field is always present when the form is POST-ed (I've learned that from other people online), is placing a hidden input with the same name attribute and a default value before the checkbox itself in HTML, like so:

<input type="hidden" name="is_admin" value="0">
<input type="checkbox" id="is_admin" name="is_admin" value="1">

Result:

  • form POST-ed and is_admin is checked: $_POST['is_admin'] will be 1
  • form POST-ed and is_admin is unchecked: $_POST['is_admin'] will be 0
1 like

Please or to participate in this conversation.