If I change the value of an input field programmatically, the input
and change
events are not firing. For example, I have this scenario:
var $input = $('#myinput');
$input.on('input', function() {
// Do this when value changes
alert($input.val());
});
$('#change').click(function() {
// Change the value
$input.val($input.val() + 'x');
});
<input id="myinput" type="text" />
<button id="change">Change value</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
The problem: The event is triggered when I type in the textfield, but not when I press the button. Is there a way to achieve this with some kind of event or otherwise without having to do it manually?
What I don't want to do: I could go through all my code to add a trigger
or function call everywhere manually, but that's not what I'm looking for.
Why: The main reason I would like to do this automatically is that I have a lot of input fields and a lot of different places where I change these inputs programmatically. It would save me a lot of time if there was a way to fire the event automatically when any input is changed anywhere in my code.
Simple solution:
Trigger
input
after you callval()
:Specific solution:
As mentioned you don't want to trigger
input
manually. This solution triggers the event automatically by overridingval()
.Just add this to your code:
See JSFiddle Demo
PS
Notice
this.is('input:text')
in the condition. If you want to trigger the event for more types, add them to the condition.There are some ways on how to achieve it. Here, you can use the levelup HTML's
oninput()
event that occurs immediately when an element is changed and call the function..
Or this jQuery,
input
thing (just related to above example)..
You can also use javascript
setInterval()
which constantly runs with a given interval time. It's only optional and best if you're doing time-related program..
jQuery listeners only work on actual browser events and those aren't thrown when you change something programmatically.
You could create your own miniature jQuery extension to proxy this so that you always trigger the event but only have to do in one modular place, like so:
Then, just call your new function whenever you want to update your text field, instead of using jQuery's 'val' function:
Here's a version working with a proxy function:
For reference, this question has really already been answered here: Why does the jquery change event not trigger when I set the value of a select using val()?
and here: JQuery detecting Programatic change event
Let's try the same thing using
.change()
event:Or you need to trigger it manually:
Snippet
The change event only fire when input blur.