问题
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'.
回答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));
回答2:
I used:
$('#selector').val(quantity).trigger("input");
回答3:
Why not just append to val()
?
$("#button").click(function(){
$("#input").val(
$("#input").val() + "a"
);
})
回答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);
})
回答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');
})
回答6:
In case you need to take into account the current cursor and text selection...
This wasn't working for me for an AngularJS app on Chrome. Someone pointed out the trigger event will not make the character visible in the input field (at least, that's what I was seeing). In addition, the previous solutions don't take into account the current cursor position and text selection in the input field. I had to use a wonderful library jquery-selection.
I have a custom on-screen numeric keypad that fills in multiple input fields. I had to...
- On focus, save the lastFocus.element
On blur, save the current text selection (start and stop)
var pos = element.selection('getPos') lastFocus.pos = { start: pos.start, end: pos.end}
When a button on the my keypad is pressed:
lastFocus.element.selection( 'setPos', lastFocus.pos) lastFocus.element.selection( 'replace', {text: myKeyPadChar, caret: 'end'})
回答7:
you don't need keypress or any other event of input just use val
.. and focus it...
try this
$("#button").click(function(){
$("#input").val('a').focus();
})
fiddle here
来源:https://stackoverflow.com/questions/15545557/how-to-trigger-an-input-event-with-jquery