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

Ben picture Ben · Oct 18, 2012 · Viewed 222k times · Source

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

Answer

Man Programmer picture Man Programmer · Oct 18, 2012
$(document).ready(function(){
    $('#TextBoxId').keypress(function(e){
      if(e.keyCode==13)
      $('#linkadd').click();
    });
});