How to trigger an input event with jQuery?

2020-03-09 07:18发布

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'.

7条回答
再贱就再见
2楼-- · 2020-03-09 07:51

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');
})
查看更多
手持菜刀,她持情操
3楼-- · 2020-03-09 07:52

I used:

$('#selector').val(quantity).trigger("input");
查看更多
▲ chillily
4楼-- · 2020-03-09 07:57

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);
})
查看更多
Melony?
5楼-- · 2020-03-09 08:02

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...

  1. On focus, save the lastFocus.element
  2. On blur, save the current text selection (start and stop)

    var pos = element.selection('getPos')
    lastFocus.pos = { start: pos.start, end: pos.end}
    
  3. When a button on the my keypad is pressed:

    lastFocus.element.selection( 'setPos', lastFocus.pos)
    lastFocus.element.selection( 'replace', {text: myKeyPadChar, caret: 'end'})
    
查看更多
Melony?
6楼-- · 2020-03-09 08:03

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

查看更多
倾城 Initia
7楼-- · 2020-03-09 08:10

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));

查看更多
登录 后发表回答