Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: "onchange" event does not work with "value" change in "text input" object

I have a javascript input object with type="text" coming along with an onchange event which is created by (related lines):

var id_box = document.createElement('input');
id_box.id = 'id_box';
id_box.type = 'text';
id_box.onchange = function()
{
    alert("Changed!");
}

For changing this value in this input field I use:

var a = document.createElement('a');
a.innerHTML = "A";
a.onclick = function()
{
    document.getElementById('id_box').value = 'A';
}

The onchange event works only changing value by keyboard typing but not for changing value by above function. Is there any way to make this works?

Please take a look at this: http://jsfiddle.net/zCMdV/7/

like image 822
Protocole Avatar asked Jul 26 '11 07:07

Protocole


People also ask

How do I use Onchange input field?

Definition and UsageThe 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 does Onchange event work 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.


1 Answers

What browser are you using?

I have made this example, which works for me... the subtle change is that I add the event to the input before I append it to the div element.

<div id="test"></div>
<script type="text/javascript">
    var id_box = document.createElement('input');
    id_box.type = 'text';
    id_box.onchange = function()
    {
        alert("Changed!");
    }
    document.getElementById("test").appendChild(id_box);

</script>

See it in action on JS Fiddle: http://jsfiddle.net/Sohnee/zCMdV/

Update:

If you are going to automate the changing of the value, you can do the same to trigger the change event...

http://jsfiddle.net/Sohnee/zCMdV/10/

document.getElementById('id_box').onchange();
like image 142
Fenton Avatar answered Sep 21 '22 11:09

Fenton