Trigger a button click with JavaScript on the Enter key in a text box

后端 未结 30 2530
难免孤独
难免孤独 2020-11-21 23:53

I have one text input and one button (see below). How can I use JavaScript to trigger the button\'s click event when the Enter key is pressed ins

30条回答
  •  滥情空心
    2020-11-22 00:55

    One basic trick you can use for this that I haven't seen fully mentioned. If you want to do an ajax action, or some other work on Enter but don't want to actually submit a form you can do this:

    Setting action="javascript:void(0);" like this is a shortcut for preventing default behavior essentially. In this case a method is called whether you hit enter or click the button and an ajax call is made to load some data.

提交回复
热议问题