0

I've got a stand-alone input field, not part of any form.

I also got a button, that has some onclick event.

When I type something in the input field, and press the Enter key, I want it do effectively press the button, or trigger its onclick event. So that the button is "the input field's default button" so to speak.

<input id='myText' type='text' />
<button id='myButton' onclick='DoSomething()'>Do it!</button>

I guess I can mess around with the input field's onkeypress or onkeydown events and check for the Enter key, etc.

But is there a more 'clean' way, I mean something that associated the button with that input field, so that the button is the 'default action' or something for that field?

Note that I'm not inside a form, I am not sending, posting, or submitting something. The DoSomething() function just changes some of the HTML content locally, depending on the text input.

Sheldon Pinkman
  • 1,086
  • 4
  • 15
  • 21
  • No, you can't do this without creating a `form` or messing with `onKeypress` event on your textbox. See an old question http://stackoverflow.com/questions/155188/trigger-a-button-click-with-javascript-on-the-enter-key-in-a-text-box – lastr2d2 Oct 25 '13 at 10:03

3 Answers3

2

Change the HTML to:

<form onsubmit="DoSomething();">
  <input id='myText' type='text' />
  <input type="submit" value="Do it!" />
</form>

Submit buttons (in a form) are automatically triggered you press enter.

Make sure you cancel the submit event though, you don't want to browser to relocate.

Cancel the default with: event.preventDefault() or have your function return false.

Halcyon
  • 57,230
  • 10
  • 89
  • 128
  • Oh right, I see, putting it in a form anyway, moving the javascript function to the form's onsubmit, and returning false there not to actually submit or send something. Yeah that looks good, thanks! – Sheldon Pinkman Oct 25 '13 at 10:11
0

Try to separate your javascript from your markup.

HTML

<form id="myform">
  <input id='myText' type='text' />
  <input type="submit" value="Do it!" />
</form>

JS

$("#myform").submit(function(e) {
     // do something
     e.preventDefault();
});

EDIT:

If you don't want to use a form then you can simply do:

$("#mybutton").on('click', function(){
     // Do something
});
-1

The better solutions is not use the html javascript events, is older. Better its separate code in layers like MVC, html is the view and .js is the controller

I create a file functions.js

jQuery("#myButton").on("click", function() {DoSomething()});
Jesús Quintana
  • 1,803
  • 13
  • 18
  • Not sure what you mean here, how does this do anything with the 'myText' field? (also, I don't use jQuery in this case, is there a non-jQuery equivalent to what you suggest?) – Sheldon Pinkman Oct 25 '13 at 10:07