tomphilps
tomphilps

Reputation: 159

Checkbox input evaluates as checked despite checked not being set

So I'm trying to figure out why the following is evaluating as true, I always thought if the checked attribute was omitted, then it wouldn't evaluate as checked. I've double checked the below to make sure the state isn't changing due to some JS. Also verified on Chrome, Safari and Firefox and all evaluate this to a checkbox being checked. Any ideas why?

<input type="checkbox" name="shipping[same_as_billing]" id="shipping:same_as_billing" value="1" onclick="shipping.setSameAsBilling(this.checked);">

Upvotes: 1

Views: 502

Answers (2)

Barr J
Barr J

Reputation: 10929

Do console log for your check box like this:

<input type="checkbox" onclick="console.log(this.defaultChecked)"/>

If your checkbox is default checked, then the value of this.checked will set to true until you change it.

if you want the defaulted to be false, change it by setting:

this.defaultChecked = false; 

Taken from W3SC:

The defaultChecked property returns the default value of the checked attribute.

This property returns true if the checkbox is checked by default, otherwise it returns false.

Upvotes: 0

Manikant Gautam
Manikant Gautam

Reputation: 3591

you can put simple onclick function as. where this.checked set status of checkbox either checked or not.

function setSameAsBilling(status){
  console.log(status);
  if(status == true){
    console.log('checked')
    return true;
  }else{
    console.log('Not checked')
   return false;
 }

}
<input type="checkbox" name="shipping[same_as_billing]" id="shipping:same_as_billing" value="1" onclick="setSameAsBilling(this.checked);">

Upvotes: 1

Related Questions