Majid Abbasi
Majid Abbasi

Reputation: 1531

Javascript on change for checkbox

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.

Upvotes: 7

Views: 13610

Answers (6)

Teocci
Teocci

Reputation: 8885

I think it is more easy just define a onchange function into the input element like this:

const wrapperElement = document.querySelector('.wrapper')
const fruits = ['apple', 'orange', 'banana']

fruits.forEach(f => {
  const item = document.createElement('div')
  item.className = 'item'

  const fruit = document.createElement('input')
  fruit.type = 'checkbox'
  fruit.id = f
  fruit.onchange = handleOnChange

  const label = document.createElement('label')
  label.className = 'checkbox-label'
  label.setAttribute('for', f)
  label.textContent = f


  item.append(fruit)
  item.append(label)

  wrapperElement.append(item)
})


function handleOnChange(e) {
  const element = e.srcElement
  element.parentElement.classList.toggle('checked')
}
.item.checked {
  background: red;
}
<div class="wrapper"></div>

Upvotes: 1

Majid Abbasi
Majid Abbasi

Reputation: 1531

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');
        }
    }

Upvotes: 1

Michael Troger
Michael Troger

Reputation: 3497

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]');

Upvotes: 4

guest271314
guest271314

Reputation: 1

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
})

Upvotes: 1

brk
brk

Reputation: 50291

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
        }
    });

Upvotes: 2

Seif Sayed
Seif Sayed

Reputation: 803

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/

Upvotes: 4

Related Questions