Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript checkbox onChange

People also ask

Can you use onChange on checkbox?

Use onChange as Attribute on Checkbox in JavaScript The instance here has a checkbox, and when checked, it will run a function that will depict the change. The keyword this refers to a global object, and the onChange attribute grabs and triggers the Check function. The value.

Do something when checkbox is checked JS?

Checking if a checkbox is checked First, select the checkbox using a DOM method such as getElementById() or querySelector() . Then, access the checked property of the checkbox element. If its checked property is true , then the checkbox is checked; otherwise, it is not.

What is onChange event in JavaScript?

The onchange event occurs when the value of an element has been changed. For radiobuttons and checkboxes, the onchange event occurs when the checked state has been changed.

What is the event for checkbox?

Checkbox event handling using pure Javascript There are two events that you can attach to the checkbox to be fired once the checkbox value has been changed they are the onclick and the onchange events.


function calc()
{
  if (document.getElementById('xxx').checked) 
  {
      document.getElementById('totalCost').value = 10;
  } else {
      calculate();
  }
}

HTML

<input type="checkbox" id="xxx" name="xxx" onclick="calc();"/>

Pure javascript:

const checkbox = document.getElementById('myCheckbox')

checkbox.addEventListener('change', (event) => {
  if (event.currentTarget.checked) {
    alert('checked');
  } else {
    alert('not checked');
  }
})
My Checkbox: <input id="myCheckbox" type="checkbox" />

If you are using jQuery.. then I can suggest the following: NOTE: I made some assumption here

$('#my_checkbox').click(function(){
    if($(this).is(':checked')){
        $('input[name="totalCost"]').val(10);
    } else {
        calculate();
    }
});

Use an onclick event, because every click on a checkbox actually changes it.