简体   繁体   中英

onchange event of text box not working if i change text value dynamically

Onchange Event Fired when i change on textbox but when i am trying to change textbox value dynamically it doesnot fired why?

here is my simple demo when i click on button i changed textbox value dynamically but still textbox onchange event doesnot fired.

<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>

<h1>My First Heading</h1>
<p>My first paragraph.</p>
<input type="text" id="txtno" value="" onchange="javascript:alert('Hi');">
<input type="button" id="btnadd" value="ClickMe">

<script>
$(document).ready(function(){
    $("#btnadd").click(function(){
        $("#txtno").val('Hello'); 
    });
});
</script>

</body>
</html>

Changing value of input via JS will not trigger .onChange events. You must trigger it manually

$('#room_1').trigger('change');

I don't see where you change input field value in your code.

The 'change' event is only fired on controls when the user commits a value change. If you make changes to a field programatically then you need to trigger the 'change' event.

In this case:

<script>
$(document).ready(function(){
    $("#btnadd").click(function(){
        $("#txtno").val('Hello').trigger('change');
    });
});
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM