/    Sign up×
Community /Pin to ProfileBookmark

Click on button when the user types Enter

Hi everyone,

I would like to add JavaScript code that whenever a user types the Enter button into a specific text box it will click on a specific button on the page.

Thank you in advance,
Samuel

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@toicontienMay 12.2009 — Something like this might help:
[CODE]function associateField(field, buttonName) {
field = (typeof(field) == "string") ? document.getElementById(field) : field;
buttonName = buttonName || field.name + "_button";
return function(e) {
if (e.keyCode == 13) {
this.form.elements[buttonName].click();
return false;
}
};
}[/CODE]

And to use it:
[CODE]// Get node reference to <input type="text" name="foo" id="my_text_box">
var el = document.getElementById("my_text_box");

// Case A:
el.onkeypress = associateField(el, "button_name");

// Case B:
el.onkeypress = associateField(el); // Button name is assumed to be "foo_button"[/CODE]

And the HTML:
[CODE]Case A:
<input type="text" name="foo" id="my_text_box">
<input type="submit" name="button_name">

Case B:
<input type="text" name="foo" id="my_text_box">
<input type="submit" name="foo_button">[/CODE]


The keyCode you need to detect is 13, which is the code for the ENTER key.
×

Success!

Help @smshulman spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.2,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,

tipper: @Samric24,
tipped: article
amount: 1000 SATS,
)...