Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML JavaScript onChange Handler is not called when updated programatically

I have found an odd anomaly with HTML text boxes and JavaScript that I have narrowed down to being a html/javascript peculiarity and I'm hoping someone can educate me on.

I have downloaded and implemented a calendar plug-in that creates a simple layer with a calendar and on selection, passes the selected date back to the text box.

What I want to do is catch when the text box changes (using onchange) and then call an Ajax function to update the database...

The problem is, onchange never gets called... I have been able to prove it with this very simple code below... When the button is clicked it changes the value which should then trigger the onchange and display an alert box...

<input type="button" name="setValue" id="setValue" value="setValue" onClick="document.getElementById('textinput').value='Updated'">&nbsp;
<input type="button" name="clearValue" id="clearValue" value="clearValue" onClick="document.getElementById('textinput').value=''"><br>
<input type="text" name="textinput" id="textinput" onChange="alert(this.name)">

Is this standard? Is there a workaround?

like image 846
php-b-grader Avatar asked Oct 28 '10 08:10

php-b-grader


People also ask

How do you call Onchange in HTML?

The onchange attribute fires the moment when the value of the element is changed. Tip: This event is similar to the oninput event. The difference is that the oninput event occurs immediately after the value of an element has changed, while onchange occurs when the element loses focus.

Why is Onchange not working?

onchange is not fired when the value of an input is changed. It is only changed when the input's value is changed and then the input is blurred. What you'll need to do is capture the keypress event when fired in the given input. Then you'll test the value of the input against the value before it was keypressed.

How can I trigger an Onchange event manually in JavaScript?

document. querySelector('#test'). addEventListener('change', () => console. log("Changed!"))

How do I programmatically force an onchange event on an input?

To programmatically force an onchange event on an input with JavaScript, we use the Event constructor. const element = document. getElementById("input"); const event = new Event("change"); element.


1 Answers

The onchange event is not triggered by a programmatic change of the value of the textinput. You have to call the code you want to execute after you change the value yourself.

like image 109
michalstanko Avatar answered Nov 15 '22 05:11

michalstanko