How to trigger an input event with jQuery?
70,362
Solution 1
like this?? Sorry, I'm confused with your writings..
$("#button").click(function(){
$("#input").trigger("keypress") // you can trigger keypress like this if you need to..
.val(function(i,val){return val + 'a';});
});
reference: .val(function(index, value));
Solution 2
I used the trigger method:
$('#selector').val(quantity).trigger("input");
Solution 3
Why not just append to val()
?
$("#button").click(function(){
$("#input").val(
$("#input").val() + "a"
);
})
Solution 4
I have known how to deal with it.
Add a eventListener on keypress event to the input and use val to change the value.
In this way there is no need to trigger focus event.
$("#button").click(function(){
var e = jQuery.Event("keypress");
e.chara = 'a';
$("#input").trigger(e);
});
$("#input").keypress(function(e){
$(this).val(e.chara);
})
Solution 5
According to the documentation
Although .trigger() simulates an event activation, complete with a synthesized event object, it does not perfectly replicate a naturally-occurring event.
so the best you could do is
$("#button").click(function(){
$("#input").trigger("focus").val($("#input").val() + 'a');
})
Related videos on Youtube
Author by
user1990553
Updated on July 09, 2022Comments
-
user1990553 almost 2 years
I want to add 'a' to the value of input when click a button
Here is my code(with jQuery 1.4.4):
$("#button").click(function(){ $("#input").trigger("focus"); var e = jQuery.Event("keypress"); e.which = '97'; $("#input").trigger(e); })
However, it seems only to trigger "focus" event, but failed to "keypress".
-
Arun P Johny about 11 yearsAs per the trigger doc , it does not perfectly replicate a naturally-occurring event.
-
ahren about 11 yearsWorks for me: jsfiddle.net/2YuN5/1 ...ah wait, I'm using jQuery 1.9... Time for you to do an update.
-
-
user1990553 about 11 yearsBecause I want to write a demo like fancyInput. And the origin event should be another keypress.Here i use click to simplify the code.
-
Luminita Balas almost 7 yearsThe val() and trigger() methods are chained to the selector.
-
Uyghur Lives Matter almost 7 yearsMy mistake. I didn't realize
.val(quantity)
was chained unlike an empty.val()
. -
Ben in CA about 4 yearsYou can also use .trigger('change') if you're listening or a change vs. input.