Home > other >  Use onchange or other
Use onchange or other

Time:12-16

I have this piece of code.

It is an input of type checkbox that has an onchange that calls a function. My thought was that when I change the checkbox from true to false in the page this function (QuitarEmisionNormal) would be executed, but it is not doing it. I don't know if I should use another way

<input type="checkbox" name="<%=Html.Encode(item.Idwarehousereceipt)%>" id="<%=Html.Encode(item.Idwarehousereceipt)%>" value="true" checked="checked" onchange="QuitarEmisionNormal(this)" />

This would be the method that I am trying to call

function QuitarEmisionNormal(checkbox) {
    alert("It works");
    QuitarImprimidoEtiquetaNormal($(checkbox).attr("id").split("_")[0], $(checkbox).prop("checked")), checkbox);
}

CodePudding user response:

Try using onclick instead of onchange since the change event only fires when the user commits a value change (ex: when the focus of your checkbox is changed). It is likely that you are not seeing your alert because your value change is not being committed.

Source: https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onchange

CodePudding user response:

I found the bug, the onchange is working, what happens is that I don't get the alert because the method I'm calling below is not working xD. Thanks for the help

CodePudding user response:

You should be use MutationObserver to listen that events.

MutationObserver tracks changes in the DOM structure. By creating an instance and calling the observe() method, MutationObserver will call the callback function every time any element attribute changes.

User changes to the input can be monitored with the oninput event.

ckbox.oninput = e => console.log(ckbox.checked);


var observer = new MutationObserver(function (mutations) {
    console.log(mutations)
});
observer.observe(ckbox, {
    attributes: true
});

btnOn.onclick=() => ckbox.setAttribute('checked','checked');
btnOff.onclick=() => ckbox.removeAttribute('checked');
<input id="ckbox" type="checkbox"/>
<button id="btnOn">Check</button>
<button id="btnOff">UnCheck</button>

If you use ckbox.checked property, you can track these changes by redefining the property by Object.defineProperty():

ckbox.oninput = e => console.log(ckbox.matches(':checked'));


var observer = new MutationObserver(function(mutations) {
  console.log(mutations)
});
observer.observe(ckbox, {
  attributes: true
});

btnOn.onclick = () => ckbox.checked = true;
btnOff.onclick = () => ckbox.checked = false;

Object.defineProperty(
  HTMLInputElement.prototype,
  'checked', {
    get() {
      return this.hasAttribute('checked');
    },
    set(value) {
      if (value) {
        this.setAttribute('checked', 'checked');
      } else {
        this.removeAttribute('checked');
      }
    }
  }
)
<input id="ckbox" type="checkbox" />
<button id="btnOn">Check</button>
<button id="btnOff">UnCheck</button>

  • Related