Search code examples
javascripthtmlcheckboxonchangechecked

Checkbox is unchecked, but it loads as checked


Some checkbox are loading, with required option. They are not checked at begin. With 'inputCHKChange' function, we should to update checkbox. So it's update checkbox as it's checked or not.

Problem is checkbox are not checked at begin. but during the load they are checked. How could to manage it?

The html:

<fieldset><div class="form-check"><label class="form-check-label"><input onchange="inputCHKChange(this);" type="checkbox" class="form-check-input" name="undefined[]" checked="false" required="">A</label></div><div class="form-check"><label class="form-check-label"><input onchange="inputCHKChange(this);" type="checkbox" class="form-check-input" name="undefined[]" checked="false" required="">B</label></div></fieldset>

The script:

function inputCHKChange(objInput) {
objInput.setAttribute('checked', objInput.checked);
}

Sample on jsfiddle.net


Solution

  • The attribute for checked is set to false:

    checked="false" 
    

    Any value in the checked attribute, or even the presence of the checked attribute, will mark the checkbox as checked. Remove the attribute and the default value of unchecked will be shown.

    Example: the checked attribute is completely removed.

    <div class="form-check">
      <label class="form-check-label">
        <input onchange="inputCHKChange(this);"
               type="checkbox" 
               class="form-check-input" 
               name="undefined[]" 
               required="">A</label>
    </div>