cleverpaul
cleverpaul

Reputation: 935

How can I use Javascript to tell whether an HTML input field has been changed by the browser?

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

Answers (1)

Shubham Khatri
Shubham Khatri

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");

JSFIDDLE

Upvotes: 3

Related Questions