简体   繁体   English

Java更改的输入字段的更改

[英]Onchange of a input field changed by Javascript

I have a input field type="hidden" which is changed by javascript itself. 我有一个输入字段type="hidden" ,该字段由javascript本身更改。

When this field changes i want an event/function to be triggered. 当此字段更改时,我希望触发事件/功能。

Tried this: 试过这个:

$(".product_id").on("change paste keyup input", function(event){alert('1');});
$(".product_id").blur(function(event){alert('1');});
$(".product_id").keypress(function(event){alert('1');});

But it does not seem to work as the value is changed by other JavaScript file itself. 但这似乎不起作用,因为其他JavaScript文件本身已更改了该值。

I cannot change or add to the existing JavaScript. 我无法更改或添加到现有JavaScript。 I cannot add anything to the input field. 我无法在输入字段中添加任何内容。

You can use jQuery's trigger method & change event. 您可以使用jQuery的trigger方法和change事件。

Changes in value to hidden elements don't automatically fire the .change() event. 对隐藏元素的值更改不会自动触发.change()事件。 So, as soon as you change the hidden inputs, you should tell jQuery to trigger it using .trigger('change') method. 因此,一旦您更改了隐藏的输入,就应该告诉jQuery使用.trigger('change')方法来触发它。

You can do it like this: 您可以这样做:

 $(function() { $("#field").on('change', function(e) { alert('hidden field changed!'); }); $("#btn").on('click', function(e) { $("#field").val('hello!').trigger('change'); console.log('Hidden Filed Value: ' + $('#field').val()); }); console.log('Hidden Filed Value: ' + $('#field').val()); }) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input id="field" type="hidden" name="name"> <button id="btn"> Change Hidden Field Value </button> 

Hope this helps! 希望这可以帮助!

It's just a hack if you can't trigger change event from sources. 如果您无法从源中触发change事件,那只是一个黑客。

May not be a good solution with setInterval() . 使用setInterval()可能不是一个好的解决方案。 But helps in the cases where you can't trigger change event from sources which are changing the hidden input value. 但是,在无法从正在更改hidden input值的源中触发change事件的情况下,这hidden

 $("#input")[0].oninput = function(){ $("#hidden").val($(this).val()); //setting hidden value } var oldVal = $("#hidden").val(); setInterval(function(){ //listening for changes var newVal = $("#hidden").val(); if(newVal !== oldVal){ console.log(newVal); oldVal = newVal; } }, 1000); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <input type="hidden" id="hidden"> <input type="text" id="input"> 

var element = $(".product_id");
element.on("change", function(){
    alert('hey');
}).triggerHandler('change');

and we need to trigger it programmatically like: 我们需要以编程方式触发它,例如:

$('.product_id').val('abcd').triggerHandler('change');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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