Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to trigger HTML button when you press Enter in textbox?

So the code that I have so far is:

<fieldset id="LinkList">
    <input type="text" id="addLinks" name="addLinks" value="http://">
    <input type="button" id="linkadd" name="linkadd" value="add">
</fieldset>

It is not in a <form> and is just as it is within a <div>. However when I type something into the textbox called "addLinks" I want the user to be able to press Enter and trigger the "linkadd" button which will then run a JavaScript function.
How can I do this?
Thanks

Edit: I did find this code, but it doesnt seem to work.

$("#addLinks").keyup(function(event){
    if(event.keyCode == 13){
        $("#linkadd").click();
    }
});
like image 427
Ben Avatar asked Oct 18 '12 12:10

Ben


People also ask

How do you trigger button click on Enter in HTML?

To trigger a click button on ENTER key, We can use any of the keyup(), keydown() and keypress() events of jQuery. keyup(): This event occurs when a keyboard key is released. The method either triggers the keyup event, or to run a function when a keyup event occurs.

How do I link a text box to a button in HTML?

Linking Submit buttons using Anchor Tag is Easy and Reliable method in HTML. We need to Write/Declare Submit button between Anchor tag's Starting and Closing tags. By using Anchor tag's href attribute we can give a Path where we want to Link our Submit Button.

How do you make a button submit on enter?

You don't need to use JavaScript to do submit button or input on entering key pressed. Just need to mark it up with type="submit" , and the other buttons mark them with type="button" .

How do you trigger a click button?

and a trigger to execute the button1 click event handler. $("#button2"). bind("click", (function () { alert("Button 2 is clicked!"); $("#button1").


10 Answers

$(document).ready(function(){
    $('#TextBoxId').keypress(function(e){
      if(e.keyCode==13)
      $('#linkadd').click();
    });
});
like image 87
Man Programmer Avatar answered Oct 08 '22 09:10

Man Programmer


It is, yeah, 2021. And I believe this still holds true.


DO NOT USE keypress

  1. keypress event is not triggered when the user presses a key that does not produce any character, such as Tab, Caps Lock, Delete, Backspace, Escape, left & right Shift, function keys(F1 - F12).

keypress event Mozilla Developer Network

The keypress event is fired when a key is pressed down, and that key normally produces a character value. Use input instead.

  1. It has been deprecated.

keypress event UI Events (W3C working draft published on November 8, 2018.)

  • NOTE | The keypress event is traditionally associated with detecting a character value rather than a physical key, and might not be available on all keys in some configurations.
  • WARNING | The keypress event type is defined in this specification for reference and completeness, but this specification deprecates the use of this event type. When in editing contexts, authors can subscribe to the beforeinput event instead.

DO NOT USE KeyboardEvent.keyCode

  1. It has been deprecated.

KeyboardEvent.keyCode Mozilla Developer Network

Deprecated | This feature is no longer recommended. Though some browsers might still support it, it may have already been removed from the relevant web standards, may be in the process of being dropped, or may only be kept for compatibility purposes. Avoid using it, and update existing code if possible; see the compatibility table at the bottom of this page to guide your decision. Be aware that this feature may cease to work at any time.


What should I use then? (The good practice)

// Make sure this code gets executed after the DOM is loaded.
document.querySelector("#addLinks").addEventListener("keyup", event => {
    if(event.key !== "Enter") return; // Use `.key` instead.
    document.querySelector("#linkadd").click(); // Things you want to do.
    event.preventDefault(); // No need to `return false;`.
});
like image 29
Константин Ван Avatar answered Oct 08 '22 09:10

Константин Ван


There are a js-free solution.

Set type=submit to the button you'd like to be default and type=button to other buttons. Now in the form below you can hit Enter in any input fields, and the Render button will work (despite the fact it is the second button in the form).

Example:

    <button id='close_renderer_button' class='btn btn-success'
            title='Перейти к редактированию программы'
            type=button>
      <span class='glyphicon glyphicon-edit'> </span> Edit program
    </button>
    <button id='render_button' class='btn btn-primary'
            title='Построить фрактал'
            type=submit
            formaction='javascript:alert("Bingo!");'>
      <span class='glyphicon glyphicon-send'> </span> Render
    </button>

Tested in FF24 and Chrome 35 (formaction is html5 feature, but type is not).

like image 39
dmitry_romanov Avatar answered Oct 08 '22 07:10

dmitry_romanov


  1. Replace the button with a submit
  2. Be progressive, make sure you have a server side version
  3. Bind your JavaScript to the submit handler of the form, not the click handler of the button

Pressing enter in the field will trigger form submission, and the submit handler will fire.

like image 33
Quentin Avatar answered Oct 08 '22 07:10

Quentin


You could add an event handler to your input like so:

document.getElementById('addLinks').onkeypress=function(e){
    if(e.keyCode==13){
        document.getElementById('linkadd').click();
    }
}
like image 24
Asad Saeeduddin Avatar answered Oct 08 '22 08:10

Asad Saeeduddin


It works when input type="button" is replaced with input type="submit" for the default button which needs to be triggered.

like image 25
Sud Avatar answered Oct 08 '22 09:10

Sud


First of all add jquery library file jquery and call it in your html head.

and then Use jquery based code...

$("#id_of_textbox").keyup(function(event){
    if(event.keyCode == 13){
        $("#id_of_button").click();
    }
});
like image 41
Milind Anantwar Avatar answered Oct 08 '22 07:10

Milind Anantwar


This should do it, I am using jQuery you can write plain javascript.
Replace sendMessage() with your functionality.

$('#addLinks').keypress(function(e) {
    if (e.which == 13) {
        sendMessage();
        e.preventDefault();
    }
});
like image 41
Anshu Avatar answered Oct 08 '22 07:10

Anshu


Based on some previous answers, I came up with this:

<form>
  <button id='but' type='submit'>do not click me</button>
  <input type='text' placeholder='press enter'>
</form>

$('#but').click(function(e) {
  alert('button press');
  e.preventDefault();
});

Take a look at the Fiddle

EDIT: If you dont want to add additional html elements, you can do this with JS only:

    $("input").keyup(function(event) {
        if (event.keyCode === 13) {
            $("button").click();
        }
    });     
like image 25
Pablo Werlang Avatar answered Oct 08 '22 08:10

Pablo Werlang


Do not use Javascript for this solution!!!

Modern HTML browsers today (and in the past) automatically submit the first form submit button they find when the ENTER/RETURN key is pressed by a user. NO JAVASCRIPT NEEDED! Browsers have worked this way for nearly 20 years but new web developers have not bothered to learn about it.

If you have multiple submit buttons in a web page or want more control, pressing the ENTER/RETURN keys will trigger submission of form data when any form field control in the web page that is associated with a submit type button or input has focus by the user, the autofocus attribute is set on any form field/button/input, or when the user tab's into any form field. The submit button for that field will then trigger when the ENTER/RETURN key is pressed. Otherwise, as mentioned above, pressing ENTER or RETURN on the keyboard automatically triggers the first available submit button for that form in the page.

So, instead of JavaScripting this, an easier solution is to just add tabindex=0 on any of your form fields or submit buttons inside a form element then autofocus on the first input control or submit button. Tabindex=0 assigns that input to the page's list of indexed tab order page items, and autofocus shifts focus to any of your form fields, triggering any submit button to respond to the ENTER/RETURN key command. The user can now press "ENTER" on their keyboard to submit the form at any point they like. This also has the advantage that the first form field is focused on and ready for data by the user. An example below:

<form id="buttonform2" name="buttonform2" action="#" method="get" role="form">
  <label for="username1">Username</label>
  <input type="text" id="username1" name="username" value="" size="20" maxlength="20" title="Username" tabindex="0" autofocus="autofocus" />
  <label for="password1">Password</label>
  <input type="password" id="password1" name="password" size="20" maxlength="20" value="" title="Password" tabindex="0" role="textbox" aria-label="Password" />
  <button id="button2" name="button2" type="submit" value="submit" form="buttonform2" title="Submit" tabindex="0" role="button" aria-label="Submit">Submit</button>
</form>

Stop scripting everything! The browsers have had this native ability for almost 20 years!!

like image 31
Stokely Avatar answered Oct 08 '22 09:10

Stokely