Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript on change for checkbox

Tags:

javascript

I am changing state of check boxes with following code:

document.getElementById('checkall').onclick = function(){
     inputs = VARIABLE.querySelectorAll('input[type=checkbox]');
     for(i=0; i<inputs.length; i++) 
          inputs[i].checked = true; 
}

This section work fine.

and i am creating checkboxes with(these codes call on for):

mainFrameInput = document.createElement("input"); mainFrameInput.className = "item"; mainFrameInput.style.display='none'; mainFrameInput.setAttribute('type', 'checkbox'); mainFrameInput.setAttribute('id', GnId);

this section work fine too

At this time i want to have a function which run when check boxes changed because it can change on several way.

I am creating check boxes with JavaScript and want to handle onchange with JavaScript NOT JQUERY.

I tested CHECKBOX_VARIABLE.onchange = function{} but it does not call when i change with above code and just CHECKBOX_VARIABLE.onclick work when i click on each checkbox.

I found solution and posted as answer.

like image 520
Majid Abbasi Avatar asked Sep 04 '16 10:09

Majid Abbasi


People also ask

Can I use Onchange with checkbox?

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.

Do something on checkbox is checked JavaScript?

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.

How do you AutoCheck a checkbox?

// Creating checkbox CheckBox Mycheckbox = new CheckBox(); Step 2: After creating CheckBox, set the AutoCheck property of the CheckBox provided by the CheckBox class.


5 Answers

one way to do this is by using the native onchange attribute and give it a function

<select id="mySelect" onchange="alert('change')">
<option value="Audi">Audi</option>
<option value="BMW">BMW</option>
<option value="Mercedes">Mercedes</option>
<option value="Volvo">Volvo</option>
</select>

here's a fiddle showing this

https://jsfiddle.net/r4aj8zh2/

like image 200
Seif Sayed Avatar answered Oct 16 '22 19:10

Seif Sayed


You can do this like that:

HTML:

<button id="checkall">check all</button><br>
a: <input type="checkbox" name="a" value="a"><br>
b: <input type="checkbox" name="b" value="b"><br>
c: <input type="checkbox" name="c" value="c">

JavaScript:

var inputs = document.querySelectorAll('input[type=checkbox]');

document.getElementById('checkall').onclick = function(){
     for(var i=0; i<inputs.length; i++) {
          inputs[i].checked = true; 
     }
     somethingChanged();
}

for(var i=0; i<inputs.length; i++) {
    inputs[i].addEventListener('change', somethingChanged);
}

function somethingChanged(evt) {
  if (evt) {
    console.log(evt.srcElement.name, 'changed');
  }
  else {
    console.log('all changed');
  }
}

Fiddle: https://jsfiddle.net/1m3rcvw9/

Explanation: When I tried it I could reproduce your problem - the change listener was not called when clicking the check-all button. So my idea is to just call the function manually after a click occurs on check-all. You can even distinguish between single checkbox clicks and check-all clicks by checking if there is a event-parameter.

EDIT: If you dynamically add <input> tags then just add the somethingChanged change listener right after creation of new elements and update the inputs variable by reselecting all checkboxes:

mainFrameInput = document.createElement("input");  
mainFrameInput.addEventListener('change', somethingChanged);
// ... insert the element into DOM here
inputs = document.querySelectorAll('input[type=checkbox]');
like image 34
Michael Troger Avatar answered Oct 16 '22 19:10

Michael Troger


You can addEventListener to these checkboxes

   // Get all checkbox. Use more specific selector using name or class
   var getAllCheckBox = document.querySelector('input[type=checkbox]');
    // Adding event listener change to each checkbox
    getAllCheckBox.addEventListener('change', function (event) {
        if (getAllCheckBox.checked) {
            // do something if checked
        } else {
            // do something else otherwise
        }
    });
like image 26
brk Avatar answered Oct 16 '22 19:10

brk


Add event listener to element when element is created. Make sure the D is lower case d at .getElementById VARIABLE = document.getElementById('#div-id');

mainFrameInput = document.createElement("input");
mainFrameInput.addEventListener("change", function() {
  // do stuff
})
like image 1
guest271314 Avatar answered Oct 16 '22 21:10

guest271314


FINALLY I RESOLVED THE ISSUE:

first of all i developed a function:

    function fireEvent(element,event){
    if (document.createEventObject){
        var evt = document.createEventObject();
        return element.fireEvent('on'+event,evt)
    }
    else{
        var evt = document.createEvent("HTMLEvents");
        evt.initEvent(event, true, true ); // event type,bubbling,cancelable
        return !element.dispatchEvent(evt);
    }
}

and called that when changed state of check box:

fireEvent(inputs[i],'change');

and added on change event when creating check boxes:

mainFrameInput.onchange = function(){ 
        if (this.checked)
        {
            console.log('checked');
        }
        else
        {
            console.log('un checked');
        }
    }
like image 1
Majid Abbasi Avatar answered Oct 16 '22 19:10

Majid Abbasi