通过Javascript更改输入字段的更改 [英] Onchange of a input field changed by Javascript
问题描述
我有一个输入字段 type =hidden
,这是由javascript本身更改的。
I have a input field type="hidden"
which is changed by javascript itself.
当这个字段更改我希望触发事件/功能。
When this field changes i want an event/function to be triggered.
试过这个:
$(".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');});
但它似乎不起作用,因为其他JavaScript文件本身更改了值。
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. I cannot add anything to the input field.
推荐答案
You can use jQuery's trigger
method & change
event.
隐藏元素的值变化不会自动触发
.change()
事件。因此,只要更改隐藏的输入,就应该告诉jQuery使用.trigger('change')
方法触发它。
Changes in value to hidden elements don't automatically fire the
.change()
event. So, as soon as you change the hidden inputs, you should tell jQuery to trigger it using.trigger('change')
method.
你可以这样做:
$(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>
希望这有帮助!
这篇关于通过Javascript更改输入字段的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!