Input textbox onchange is not firing when data is assigned to input textbox

社会主义新天地 提交于 2019-12-01 04:56:53

问题


This is my HTML page

<script>
function set()
{
document.getElementById("txt").value++;
}
</script>
<input id="txt" type="text" onchange="javascript:alert('txt changed');" value="0">
<br/>
<input type="button" onclick="set()" value="Set Data"/>

When I press the button, the text box value is changing, and the onchange event is not firing, but when I enter value manually in the textbox, it is firing the onchange.

All I want is to call a JavaScript function when data is changed in the textbox when a button is clicked.

Can you help?


回答1:


you can fire onchange from code using document.getElementById("txt").onchange(); after the changing the value through code

UPDATE

change your set function to take the id of the text box

function set(textboxid)
{
    var tb = document.getElementById(textboxid);
    tb.value++;
    tb.onchange();
}



回答2:


This appears to be a browser bug. With firebug I have logged all events in input. ANY events is triggered when you change value with function set();

I've tested in firefox.


Note: if it isn't a bug, at least is a wrong definition about how events works.



来源:https://stackoverflow.com/questions/3600680/input-textbox-onchange-is-not-firing-when-data-is-assigned-to-input-textbox

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!