如何检测来自javascript事件的输入的更改

时间:2016-08-30 09:51:04

标签: javascript jquery

我想检测输入字段的内容何时发生变化。例如,按钮的事件,我该如何检测到这种变化?

$('#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>

我希望有人有这个想法,除了这个:

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

1 个答案:

答案 0 :(得分:2)

以编程方式更改事件时不会触发事件。但是.trigger(event) / .triggerHandler(event)可用于触发事件。

&#13;
&#13;
$('#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');  
});
&#13;
<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>
&#13;
&#13;
&#13;

第二个选项是轮询不推荐

&#13;
&#13;
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');  
});
&#13;
<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>
&#13;
&#13;
&#13;