Reputation: 935
onchange="myfunction()"
The above works perfectly when I want the Javascript function "myfunction" to execute as soon as a user inputs some text into an input field however, I have a situation where the browser automatically inputs the text. How can I execute myfunction when the field is updated with the following:
document.getElementById("myfield").value = "my value"
"onchange" does not recognise DOM changes.
Upvotes: 1
Views: 91
Reputation: 281626
onchange
only fires when the user types into the input and then the input loses focus.
But you can trigger the event using:
$("#myfield").trigger("change");
$(function(){
$('#btn').click(function(){
document.getElementById('myField').value = "my value";
$('#myField').trigger('change');
});
})
function myfunction(){
alert('Value Changed');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type = "text" onChange = "myfunction()" id="myField"/>
<button id="btn">Change
</button>
onchange
only fires when the user types into the input and then the input loses focus.
But you can trigger the event using:
$("#myfield").trigger("change");
Upvotes: 3