开发者

Scripting an input element of an HTML form?

By design I need an input element typed text but I do not need an input element typed 开发者_如何转开发submit. I want to submit what's written in the input element once the enter key pressed. How would I do that in JavaScript? Do I need tags and other stuff or could I do it without them (just using )?


In Firefox at least, pushing enter in a input[type=text] element will submit it.

Check it out on JSBin.

You do not need to use JavaScript (maybe in IE, can not test that now).

Also, it's worth mentioning that all forms should have a submit button. You will need to explicitly tell the user to push enter. Also, what about devices with no enter button? I've heard the Zune can not submit forms without a button.

Some people say an exception is the search input box, like on Stack Overflow. However, I think it could still benefit from a small search button or similar.


You do not need any script. I have a small hook for you

<form id="form" action="action.php" method="get">
    <input type="text" name="login" value="login" />
    <input type="submit" value="submit" style="display: none;" />
</form>

style="display: none;" is a solution


You can watch the keypress event and read the keycode on the particular element and whenever you get the "Enter" key, you can fire the submit.

function GetKeyCode(e) {
    var code;
    if (!e) var e = window.event;
    if (e.keyCode) code = e.keyCode;
    else if (e.which) code = e.which;
    var character = String.fromCharCode(code);
    alert('Character was ' + character);
}

However most of the browsers post the form on the "Enter" key automatically.


You don't really need JavaScript for that. This should work across major desktop browsers (FF2-3,Chrome/Chromium,IE6-8,Opera6-10):

<form action="/some/action" method="POST">
   <input type="text" name="somefield">
</form>

Pressing ENTER in the input field will submit the form as usual.

Caveats:

  • (mouse) users will be confused - do you want to create a major usability problem?
  • users with disabilities (e.g. using some sort of screen reader) might not be able to submit the form - if the company is in the US, now you have a legal problem to go with the usability problem
  • mobile and/or exotic browsers may not be able to submit the form
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜