Onchange Of A Input Field Changed By 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. Tried this: $('.product_id').on('change
Solution 1:
You can use jQuery's trigger
method & change
event.
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.
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());
})
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputid="field"type="hidden"name="name"><buttonid="btn">
Change Hidden Field Value
</button>
Hope this helps!
Solution 2:
It's just a hack if you can't trigger change
event from sources.
May not be a good solution with setInterval()
. But helps in the cases where you can't trigger change
event from sources which are changing the hidden
input
value.
$("#input")[0].oninput = function(){
$("#hidden").val($(this).val()); //setting hidden value
}
var oldVal = $("#hidden").val();
setInterval(function(){ //listening for changesvar newVal = $("#hidden").val();
if(newVal !== oldVal){
console.log(newVal);
oldVal = newVal;
}
}, 1000);
<scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputtype="hidden"id="hidden"><inputtype="text"id="input">
Solution 3:
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');
Post a Comment for "Onchange Of A Input Field Changed By Javascript"