Dynamically Change the Status of Bootstrap3 Checkbox

Default Status

  • In Bootstrap3, when you add a simple check box, the default code is <input type="checkbox" />.
  • This checkbox will keep un-checked. When you check it, this default code will keep the same.
  • If you use this.getAttribute('checked') to check if checkbox is checked or not, you always get undefined.

Default Checked Status

In Bootstrap3, you can set a default checked attribute to checkbox to make it default checked: <input type='checkbox' checked/>.
If you use $(this).attr('checked') to check status, it will return checked or undefined. But if you use this.getAttribute("checked"), you will always get empty value returned.
If you use <input type='checkbox' checked = "checked"/>, $(this).attr('checked') will return same result as above, but this.getAttribute("checked") will always get checked no matter if you check it or not.

You can also set <input type='checkbox' checked="checked"/> to make it default checked.

Change Status

Following JQuery Code can divide status of checkbox if someone check or uncheck it:

//You should change 'type=checkbox' based on your code. 'name' can be skipped
if($(this).attr('checked') == undefined){
$(this).attr("checked", "checked");
//steps for a checked checkbox...
//steps for an un-checked checkbox...

The usage of code above: when you check the checkbox, this default code will become <input type='checkbox' checked='checked'>. If you un-check it, code will change back to <input type="checkbox" />.

  • In this case, if you use $(this).attr(checked) or this.getAttribute(checked) to check the status of checkbox, the un-checked checkbox will return undefined. the checked checkbox will return checked.

Check/UnCheck Checkbox Using JavaScirpt

In Bootstrap3, you can also set the checked attribute of checkbox to true or false.

If you use JQuery, $(this).attr("checked",false) will remove checked attribute in code.

If you use pure JavaScript, You have two steps to do this:

  • this.setAttribute("checked", true) or this.setAttribute("checked", "checked") can change the code but not behavior. i.e. code will become <input type='checkbox' checked='checked'> or <input type='checkbox' checked='true'>, but on user interface, checkbox is not checked

  • this.checked="checked" or this.checked = true will only change use interface. Your checkbox will be checked buy there is nothing changed in code.