Provie9 Provie9 - 3 months ago 14
jQuery Question

How to detect changed of a input from javascript event

I want to detect whenever the content of the input field has changed. For example is the event of the button, how can i detect this change?



$('#kunden_plz').on('propertychange change keyup paste input',function(){
console.log("PLZ: "+$(this).val());
});

$('#change_plz').on('click',function(){
$('#kunden_plz').val("12345");
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
<li>
<label>Plz: </label>
<input id="kunden_plz" class="plz" size="5" name="plz" value="" type="text" />
</li>
</ul>
<button id="change_plz" type="button">Change</button>





I hope someone has a idea, excepted this:

<button id='btn'>Click Me</button>
<input type='hidden'id='txtVar' value=''/>

$("#btn").click(function(){
$("#txtVar").val("1234").change();
});

$(document).on('change', '#txtVar', function () {
alert("called");
});

Answer

Event will not be triggered when you change them programmatically. However .trigger(event)/.triggerHandler(event) can be used to trigger the event.

$('#kunden_plz').on('propertychange change keyup paste input',function(){
	console.log("PLZ: "+$(this).val());
});

$('#change_plz').on('click',function(){
  $('#kunden_plz').val("12345").trigger('change');  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
  <li>
    <label>Plz: </label> 
	<input id="kunden_plz" class="plz" size="5" name="plz" value="" type="text"  /> 
  </li>
</ul>
<button id="change_plz" type="button">Change</button>

Second option is Polling Not Recommended

var previousVal;
var pollInterval = setInterval(function() {
    var val = $('#kunden_plz').val();
    if (val !== previousVal) {
      // It changed
      console.log("PLZ: "+val);
    }
    previousVal = val;
}, 100);

$('#change_plz').on('click',function(){
  $('#kunden_plz').val("12345").trigger('change');  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul>
  <li>
    <label>Plz: </label> 
	<input id="kunden_plz" class="plz" size="5" name="plz" value="" type="text"  /> 
  </li>
</ul>
<button id="change_plz" type="button">Change</button>