Trigger a button click with JavaScript on the Enter key in a text box
Asked Answered
P

31

1460

I have one text input and one button (see below). How can I use JavaScript to trigger the button's click event when the Enter key is pressed inside the text box?

There is already a different submit button on my current page, so I can't simply make the button a submit button. And, I only want the Enter key to click this specific button if it is pressed from within this one text box, nothing else.

<input type="text" id="txtSearch" />
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />
Pitts answered 30/9, 2008 at 21:32 Comment(2)
Important note for rookies like me: The key part of this question is if you already have a form on the page so already have a submit button. The jQuery answer is cross browser compatible and a good solution.Boat
@JoshuaDance, already having a form/submit is not a trouble. A page can have many forms (but not nested), each having their own submit. Every field of each form will trigger only the submit of that form. As stated by this answer.Otter
O
1545

In jQuery, the following would work:

$("#id_of_textbox").keyup(function(event) {
    if (event.keyCode === 13) {
        $("#id_of_button").click();
    }
});

$("#pw").keyup(function(event) {
    if (event.keyCode === 13) {
        $("#myButton").click();
    }
});

$("#myButton").click(function() {
  alert("Button code executed.");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Username:<input id="username" type="text"><br>
Password:&nbsp;<input id="pw" type="password"><br>
<button id="myButton">Submit</button>

Or in plain JavaScript, the following would work:

document.getElementById("id_of_textbox")
    .addEventListener("keyup", function(event) {
    event.preventDefault();
    if (event.keyCode === 13) {
        document.getElementById("id_of_button").click();
    }
});

document.getElementById("pw")
    .addEventListener("keyup", function(event) {
    event.preventDefault();
    if (event.keyCode === 13) {
        document.getElementById("myButton").click();
    }
});

function buttonCode()
{
  alert("Button code executed.");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Username:<input id="username" type="text"><br>
Password:&nbsp;<input id="pw" type="password"><br>
<button id="myButton" onclick="buttonCode()">Submit</button>
Optimistic answered 30/9, 2008 at 21:52 Comment(15)
It is probably a better practice to query event.which than event.keyCode or event.charCode, see developer.mozilla.org/en/DOM/event.charCode#NotesHolograph
@William: As he's using keyup, and your link says "charCode is never set in the keydown and keyup events. In these cases, keyCode is set instead.", it doesn't matter. That said, though, I don't think keyup is the right event for the job (keydown, I would have thought; that's how a button behaves when it has focus, for instance).Glanti
keydown not keyup is the better event to use. Also, if you are using asp.net you will have to return false at the end to stop asp.net from still intercepting the event.Buckjumper
Problem with using keydown is that holding down enter will fire the event over and over again. if you attach to the keyup event, it will only fire once the key is released.Optimistic
$(this).click(); looks nicer, and might will work with selectors that match more than one element (ie: $('.buttons'))Thorvaldsen
I used $inputs = $('#foo,#bar'); $inputs.on('keydown', ...), and $inputs.off('keydown') when received an event to prevent auto-repeat, and return false to prevent wrong button being triggered.Coworker
I've tweaked your code adding event.preventDefault(); before invoking click(); function while my page has a form and I've switched keyup with keypress as it was the only working handler for me, anyways, thanks for neat piece of code!Ansley
This works for ff, chrome, ie in a asp.net app if you change it to keydown and add event.preventDefault() before the click() event. Hate that asp.net webforms app are so sensitive to this kind of crap.Aggappera
@Hugo You can't use $(this) because the parent ID is that of the textbox, and the one you want to click() on is the button ID.Generous
Why people hate jQuery so much? Any particular reason to discourage the use of jQuery?Fachini
To be fair, jQuery was pretty much synonymous with JS back when this answer was posted. But now a lot of us who avoid jQuery altogether (because it's just a waste of kb when you're using something like React) feel annoyed when we search for answers to JS questions and often the first thing that comes up is a library we don't want to depend on.Thyrse
@sohaiby: if OP was using jquery, he would ask about it. And if he was not using jquery, suggesting it is overkill for such a simple task. It is the same as asking how to merge strings in C++ and receiving an answer about using Qt's QString. Technically valid, but not what the question was asking for.Mylor
Please use key instead of keyCode. The latter is deprecated.Calipee
I voted up, but for some reason I had to use single quotes to make it work. Like this: document.getElementById('pw') and document.getElementById('id_of_button').click();Adequate
event.keyCode worked in windows and on mac systems for me. ThanksOcam
C
437

Then just code it in!

<input type = "text"
       id = "txtSearch" 
       onkeydown = "if (event.keyCode == 13)
                        document.getElementById('btnSearch').click()"    
/>

<input type = "button"
       id = "btnSearch"
       value = "Search"
       onclick = "doSomething();"
/>
Cohesion answered 30/9, 2008 at 21:56 Comment(7)
if you need to stop the form submission:onkeydown="if (event.keyCode == 13) {document.getElementById('btnSubmit').click();event.returnValue=false;event.cancel=true;}"Hyacinthia
What about cross-browser compatibility? Does it work in all common browsers? (I see IE6 as common browser as it has still more than 5% of used browsers worldwide)Eyecatching
This worked for me due to fact that the inline method, instead of calling function with similar code in it, allows you to return false on the call and avoid postback. In my case the "click" method invokes a __doPostback async call and without the "return false;" would just reload the page.Valuation
@TimothyChung: Thanks immensely. The rest of this page is great, but I got here via Google trying to figure out how to keep an "Enter" on a text field from triggering a postback without using a <form> (which doesn't seem to work inside an asp:UpdatePanel). This works. (And it can be done inside a javascript function like kdenney's and probably in JQuery.)Mellette
I agree with Sam, this code with this inline JS-code is ugly as hell. You should always separate HTML and JavaScript codes.Dunc
Had to change onkeydown to onkeypress for it work in Chrome.Barbiturate
@Sam Never get your wisdom from puppets. Pain leads to fear, and fear is the mind-killer. Fear is the little-death that brings total obliteration. I will face my fear. I will permit it to pass over me and through me. And when it has gone past I will turn the inner eye to see its path. Where the fear has gone there will be nothing. Except maybe inline event handlers. So, yes, please separate your event handlers from your view/markup, as this answer does. ;^)Airway
P
186

Figured this out:

<input type="text" id="txtSearch" onkeypress="return searchKeyPress(event);" />
<input type="button" id="btnSearch" Value="Search" onclick="doSomething();" />

<script>
function searchKeyPress(e)
{
    // look for window.event in case event isn't passed in
    e = e || window.event;
    if (e.keyCode == 13)
    {
        document.getElementById('btnSearch').click();
        return false;
    }
    return true;
}
</script>
Pitts answered 30/9, 2008 at 21:52 Comment(3)
e = e || window.event; // shortest way to get eventCristen
Best plain JavaScript option. Added JavaScript as an attribute in HTML is space-consuming, and jQuery is just jQuery (compatibility isn't guaranteed). Thanks for the solution!Generous
and if you return false inside the if, you can avoid the key from being processed further: <input type="text" id="txtSearch" onkeypress="searchKeyPress(event);" /> <input type="button" id="btnSearch" Value="Search" onclick="doSomething();" /> <script> function searchKeyPress(e) { // look for window.event in case event isn't passed in e = e || window.event; if (e.keyCode == 13) { document.getElementById('btnSearch').click(); return false; } return true; } </script>Waldenburg
H
90

Make the button a submit element, so it'll be automatic.

<input type = "submit"
       id = "btnSearch"
       value = "Search"
       onclick = "return doSomething();"
/>

Note that you'll need a <form> element containing the input fields to make this work (thanks Sergey Ilinsky).

It's not a good practice to redefine standard behaviour, the Enter key should always call the submit button on a form.

Harlamert answered 30/9, 2008 at 21:33 Comment(5)
Dudes! Read his entire question. There's already another submit button on the page, so this wouldn't work for him.Bluebeard
Fun fact, I recently tried to do this in SharePoint. However SharePoint already has a form that wraps around all your content, and any <form> tags are thrown out by the otherwise liberal HTML parser. So I do have to hijack keypresses or bust. (BTW, pressing Enter in SharePoint launches Edit mode for some reason. I guess the ribbon is using the same form.)Extreme
A <button type="submit" onclick="return doSomething(this)">Value</button> works to. The clue lies within the return keywordArronarrondissement
@Bluebeard - OTOH, as mentioned by garrow, OP was incorrect when he stated that limitation. It is entirely possible to have multiple forms on one page: just need to wrap the element inside its own form, and make sure that is not inside the other form on the page.Hayfork
@Hayfork Of course! But we can both agree it was unclear from the original question whether multiple forms was a possibility. Another good reason to post as much of one's code as possible.Bluebeard
P
82

Since no one has used addEventListener yet, here is my version. Given the elements:

<input type = "text" id = "txt" />
<input type = "button" id = "go" />

I would use the following:

var go = document.getElementById("go");
var txt = document.getElementById("txt");

txt.addEventListener("keypress", function(event) {
    event.preventDefault();
    if (event.keyCode == 13)
        go.click();
});

This allows you to change the event type and action separately while keeping the HTML clean.

Note that it's probably worthwhile to make sure this is outside of a <form> because when I enclosed these elements in them pressing Enter submitted the form and reloaded the page. Took me a few blinks to discover.

Addendum: Thanks to a comment by @ruffin, I've added the missing event handler and a preventDefault to allow this code to (presumably) work inside a form as well. (I will get around to testing this, at which point I will remove the bracketed content.)

Putput answered 19/11, 2013 at 5:37 Comment(5)
I really don't understand why the JQeuery answer has more upvotes. I cry for the webdevelopement community.Leaseholder
All you're really missing is an argument in your keypress handler and a e.preventDefault() to get it working with forms. See my (new) answer.Airway
unless you don't intend your users to actually enter any data, you should really do something like if (event.keyCode == 13) { event.preventDefault(); go.click();} Weissman
Using jQuery just for this tiny thing is sure useless. It also works much easily with CSP and takes less time to load. If you can, use this.Roark
@Leaseholder looking back almost a decade, do you still have the same vue? Or would you react differently, maybe in a little less angular fashion? :pPutput
C
62

In plain JavaScript,

if (document.layers) {
  document.captureEvents(Event.KEYDOWN);
}

document.onkeydown = function (evt) {
  var keyCode = evt ? (evt.which ? evt.which : evt.keyCode) : event.keyCode;
  if (keyCode == 13) {
    // For Enter.
    // Your function here.
  }
  if (keyCode == 27) {
    // For Escape.
    // Your function here.
  } else {
    return true;
  }
};

I noticed that the reply is given in jQuery only, so I thought of giving something in plain JavaScript as well.

Coltson answered 8/2, 2011 at 4:49 Comment(7)
document.layers? Are you still supporting Netscape?!!Cristen
No you do not need to support Netscape. blog.netscape.com/2007/12/28/…Palp
netscape.com doesn't even exists anymore (it redirects to aol.com) and yet there are still people supporting nescape, amazing.Registrant
evt.which ? evt.which : evt.keyCode is equal to evt.which || evt.keyCodeJd
@Registrant I'd bet that's because there are still people using Netscape.Admissive
I don't understand why you check the availability of the layers feature in order to activate capturing of Event.KEYDOWN. What do those things have to do with each other? Test for if (Event.KEYDOWN) instead!Verbiage
@Registrant Well technically isp.netscape.com still exists (though it's basically the same as compuserve.com).Stonedead
F
32

Use keypress and event.key === "Enter" with modern JS!

const textbox = document.getElementById("txtSearch");
textbox.addEventListener("keypress", function onEvent(event) {
    if (event.key === "Enter") {
        document.getElementById("btnSearch").click();
    }
});

Mozilla Docs

Supported Browsers

Fractocumulus answered 18/2, 2018 at 18:57 Comment(3)
looks like keypress has been deprecatedHulsey
@Hulsey Is keydown more suitable now?Radtke
@Radtke according to Mozilla's keypress docs: "Warning: Since this event has been deprecated, you should use beforeinput or keydown instead."Hulsey
C
23

One basic trick you can use for this that I haven't seen fully mentioned. If you want to do an ajax action, or some other work on Enter but don't want to actually submit a form you can do this:

<form onsubmit="Search();" action="javascript:void(0);">
    <input type="text" id="searchCriteria" placeholder="Search Criteria"/>
    <input type="button" onclick="Search();" value="Search" id="searchBtn"/>
</form>

Setting action="javascript:void(0);" like this is a shortcut for preventing default behavior essentially. In this case a method is called whether you hit enter or click the button and an ajax call is made to load some data.

Cheddar answered 12/9, 2013 at 19:27 Comment(6)
This is a better solution for mobile device support. It automatically hides the keyboard on Android devices, and also iOS if you add searchCriteria.blur(); to the onsubmit.Casteel
This won't work, as there is already another submit button in the page.Waldenburg
@JoseGómez, a page can have as many submit buttons as the dev wishes, being triggered by their corresponding fields only. It only takes to have distinct forms for each group of fields/submit. A page is not limited to a single form.Otter
@Frederic: from the question I (mis?)understood that the other submit button was in the same form: "There is already a different submit button on my current page, so I can't simply make the button a submit button."Waldenburg
@JoseGómez, the question does not mandate to keep all in a single form. Many devs ignore they can put many forms in a single page. The way the OP has written its trouble's cause suggests he may be in that case. By example, lots of .Net webform devs believe html to be restricted to a single form per page, since .Net webform is restricted that way. But this is not a html restriction indeed.Otter
This is a great answer since it allows custom actions yet avoids the need for a bunch of fancy override code.Wrinkly
M
18

To trigger a search every time the enter key is pressed, use this:

$(document).keypress(function(event) {
    var keycode = (event.keyCode ? event.keyCode : event.which);
    if (keycode == '13') {
        $('#btnSearch').click();
    }
}
Mesics answered 27/10, 2011 at 3:35 Comment(0)
T
16

Try it:

<input type="text" id="txtSearch"/>
<input type="button" id="btnSearch" Value="Search"/>

<script>             
   window.onload = function() {
     document.getElementById('txtSearch').onkeypress = function searchKeyPress(event) {
        if (event.keyCode == 13) {
            document.getElementById('btnSearch').click();
        }
    };

    document.getElementById('btnSearch').onclick =doSomething;
}
</script>
Teide answered 2/3, 2015 at 8:4 Comment(0)
R
15

Short working pure JS

txtSearch.onkeydown= e => (e.key=="Enter") ? btnSearch.click() : 1

txtSearch.onkeydown= e => (e.key=="Enter") ? btnSearch.click() : 1

function doSomething() {
  console.log('💩');
}
<input type="text" id="txtSearch" />
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />
Rowlock answered 25/6, 2020 at 14:46 Comment(0)
L
14
onkeydown="javascript:if (event.which || event.keyCode){if ((event.which == 13) || (event.keyCode == 13)) {document.getElementById('btnSearch').click();}};"

This is just something I have from a somewhat recent project... I found it on the net, and I have no idea if there's a better way or not in plain old JavaScript.

Limey answered 30/9, 2008 at 21:56 Comment(0)
C
14

In modern, undeprecated (without keyCode or onkeydown) Javascript:

<input onkeypress="if(event.key == 'Enter') {console.log('Test')}">
Calipee answered 29/1, 2019 at 14:2 Comment(1)
This is in my opinion the simplest answer that does the job. In my use case, I upgraded it to onkeypress="inputKeyPressed(event)" and then handled the event.which parameter in the function itself. Enter key for example returns the event.which as 13.Rosalia
T
13

Although, I'm pretty sure that as long as there is only one field in the form and one submit button, hitting enter should submit the form, even if there is another form on the page.

You can then capture the form onsubmit with js and do whatever validation or callbacks you want.

Toponym answered 1/10, 2008 at 9:51 Comment(0)
E
13

This is a solution for all the YUI lovers out there:

Y.on('keydown', function() {
  if(event.keyCode == 13){
    Y.one("#id_of_button").simulate("click");
  }
}, '#id_of_textbox');

In this special case I did have better results using YUI for triggering DOM objects that have been injected with button functionality - but this is another story...

Elizebethelizondo answered 29/8, 2013 at 14:1 Comment(0)
D
12

In Angular2:

(keyup.enter)="doSomething()"

If you don't want some visual feedback in the button, it's a good design to not reference the button but rather directly invoke the controller.

Also, the id isn't needed - another NG2 way of separating between the view and the model.

Dentilabial answered 22/8, 2015 at 11:56 Comment(1)
Here's a question about further info on the keyup options: https://mcmap.net/q/46211/-what-are-the-options-for-keyup-in-angular2/435605Dentilabial
H
10

This in-case you want also diable the enter button from Posting to server and execute the Js script.

<input type="text" id="txtSearch" onkeydown="if (event.keyCode == 13)
 {document.getElementById('btnSearch').click(); return false;}"/>
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />
Haft answered 2/4, 2015 at 9:37 Comment(0)
V
9

This onchange attempt is close, but misbehaves with respect to browser back then forward (on Safari 4.0.5 and Firefox 3.6.3), so ultimately, I wouldn't recommend it.

<input type="text" id="txtSearch" onchange="doSomething();" />
<input type="button" id="btnSearch" value="Search" onclick="doSomething();" />
Vulgate answered 8/5, 2010 at 19:48 Comment(1)
Should also mention that it triggers on unfocus.Bacteroid
E
9

For jQuery mobile, I had to do:

$('#id_of_textbox').live("keyup", function(event) {
    if(event.keyCode == '13'){
    $('#id_of_button').click();
    }
});
Externality answered 16/5, 2012 at 20:44 Comment(1)
.live is deprecated in jQuery 1.7. Is it still considered OK in jQuery Mobile?Pithead
Z
9

Nobody noticed the html attibute "accesskey" which is available since a while.

This is a no javascript way to keyboard shortcuts stuffs.

accesskey_browsers

The accesskey attributes shortcuts on MDN

Intented to be used like this. The html attribute itself is enough, howewer we can change the placeholder or other indicator depending of the browser and os. The script is a untested scratch approach to give an idea. You may want to use a browser library detector like the tiny bowser

let client = navigator.userAgent.toLowerCase(),
    isLinux = client.indexOf("linux") > -1,
    isWin = client.indexOf("windows") > -1,
    isMac = client.indexOf("apple") > -1,
    isFirefox = client.indexOf("firefox") > -1,
    isWebkit = client.indexOf("webkit") > -1,
    isOpera = client.indexOf("opera") > -1,
    input = document.getElementById('guestInput');

if(isFirefox) {
   input.setAttribute("placeholder", "ALT+SHIFT+Z");
} else if (isWin) {
   input.setAttribute("placeholder", "ALT+Z");
} else if (isMac) {
  input.setAttribute("placeholder", "CTRL+ALT+Z");
} else if (isOpera) {
  input.setAttribute("placeholder", "SHIFT+ESCAPE->Z");
} else {'Point me to operate...'}
<input type="text" id="guestInput" accesskey="z" placeholder="Acces shortcut:"></input>
Zodiac answered 7/7, 2016 at 18:11 Comment(2)
Doesn't seem to answer the OP's question around the special case of key=ENTERKnowable
This answer misunderstands accesskey, which is a way to have a key focus on an element - after pressing the access key for the text area, one could then start typing into it. OP is asking for something quite different: a way to submit the contents of the current element.Hayfork
L
8
event.returnValue = false

Use it when handling the event or in the function your event handler calls.

It works in Internet Explorer and Opera at least.

Laboratory answered 22/4, 2010 at 13:53 Comment(0)
A
8

To add a completely plain JavaScript solution that addressed @icedwater's issue with form submission, here's a complete solution with form.

NOTE: This is for "modern browsers", including IE9+. The IE8 version isn't much more complicated, and can be learned here.


Fiddle: https://jsfiddle.net/rufwork/gm6h25th/1/

HTML

<body>
    <form>
        <input type="text" id="txt" />
        <input type="button" id="go" value="Click Me!" />
        <div id="outige"></div>
    </form>
</body>

JavaScript

// The document.addEventListener replicates $(document).ready() for
// modern browsers (including IE9+), and is slightly more robust than `onload`.
// More here: https://mcmap.net/q/33055/-what-is-the-non-jquery-equivalent-of-39-document-ready-39
document.addEventListener("DOMContentLoaded", function() {
    var go = document.getElementById("go"),
        txt = document.getElementById("txt"),
        outige = document.getElementById("outige");

    // Note that jQuery handles "empty" selections "for free".
    // Since we're plain JavaScripting it, we need to make sure this DOM exists first.
    if (txt && go)    {
        txt.addEventListener("keypress", function (e) {
            if (event.keyCode === 13)   {
                go.click();
                e.preventDefault(); // <<< Most important missing piece from icedwater
            }
        });

        go.addEventListener("click", function () {
            if (outige) {
                outige.innerHTML += "Clicked!<br />";
            }
        });
    }
});
Airway answered 23/12, 2015 at 18:51 Comment(0)
N
8

For those who may like brevity and modern js approach.

input.addEventListener('keydown', (e) => {if (e.keyCode == 13) doSomething()});

where input is a variable containing your input element.

Nila answered 28/1, 2018 at 15:41 Comment(0)
F
5
document.onkeypress = function (e) {
 e = e || window.event;
 var charCode = (typeof e.which == "number") ? e.which : e.keyCode;
 if (charCode == 13) {

        // Do something here
        printResult();
    }
};

Heres my two cents. I am working on an app for Windows 8 and want the button to register a click event when I press the Enter button. I am doing this in JS. I tried a couple of suggestions, but had issues. This works just fine.

Frontward answered 19/5, 2014 at 12:40 Comment(1)
Sort of overkill to place the event handler on the document. If you had a charCode of 13 anywhere else, you're firing off the printResult().Airway
S
5

To do it with jQuery:

$("#txtSearch").on("keyup", function (event) {
    if (event.keyCode==13) {
        $("#btnSearch").get(0).click();
    }
});

To do it with normal JavaScript:

document.getElementById("txtSearch").addEventListener("keyup", function (event) {
    if (event.keyCode==13) { 
        document.getElementById("#btnSearch").click();
    }
});
Shwalb answered 12/6, 2015 at 18:5 Comment(1)
getElementById takes the id of the element without the hash.Lymphangitis
S
4

In jQuery, you can use event.which==13. If you have a form, you could use $('#formid').submit() (with the correct event listeners added to the submission of said form).

$('#textfield').keyup(function(event){
   if(event.which==13){
       $('#submit').click();
   }
});
$('#submit').click(function(e){
   if($('#textfield').val().trim().length){
      alert("Submitted!");
   } else {
    alert("Field can not be empty!");
   }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="textfield">
Enter Text:</label>
<input id="textfield" type="text">
<button id="submit">
Submit
</button>
Sporocyst answered 9/7, 2018 at 22:4 Comment(0)
D
2

These day the change event is the way!

document.getElementById("txtSearch").addEventListener('change',
    () => document.getElementById("btnSearch").click()
);
Dayle answered 17/8, 2020 at 7:12 Comment(1)
change events fire when the user commits a value change to a form control. This may be done, for example, by clicking outside of the control or by using the Tab key to switch to a different control. MDN I think a lot of people wouldn't want this behaviour...Silicium
M
2

My reusable Vanilla JS solution. so you can change which button gets hit depending on what element/textbox is active.

 <input type="text" id="message" onkeypress="enterKeyHandler(event,'sendmessage')" />
 <input type="button" id="sendmessage" value="Send"/>

function enterKeyHandler(e,button) {
    e = e || window.event;
    if (e.key == 'Enter') {
        document.getElementById(button).click();
    }
}
Mendive answered 30/6, 2022 at 19:49 Comment(0)
W
2

You can try below code in jQuery.

$("#txtSearch").keyup(function(e) {
    e.preventDefault();
    var keycode = (e.keyCode ? e.keyCode : e.which);
    if (keycode === 13 || e.key === 'Enter') 
    {
        $("#btnSearch").click();
    }
});
Warrant answered 4/9, 2022 at 18:23 Comment(0)
O
-1

I have developed custom javascript to achieve this feature by just adding class

Example: <button type="button" class="ctrl-p">Custom Print</button>

Here Check it out Fiddle

// find elements
var banner = $("#banner-message")
var button = $("button")

// handle click and add class
button.on("click", function(){
    if(banner.hasClass("alt"))
    banner.removeClass("alt")
  else
    banner.addClass("alt")
})

$(document).ready(function(){
    $(document).on('keydown', function (e) {
        
         if (e.ctrlKey) {
            $('[class*="ctrl-"]:not([data-ctrl])').each(function (idx, item) {
                var Key = $(item).prop('class').substr($(item).prop('class').indexOf('ctrl-') + 5, 1).toUpperCase();
                $(item).attr("data-ctrl", Key);
                $(item).append('<div class="tooltip fade top in tooltip-ctrl alter-info" role="tooltip" style="margin-top: -61px; display: block; visibility: visible;"><div class="tooltip-arrow" style="left: 49.5935%;"></div><div class="tooltip-inner"> CTRL + ' + Key + '</div></div>')
            });
        }
         
        if (e.ctrlKey && e.which != 17) {
            var Key = String.fromCharCode(e.which).toLowerCase();
            if( $('.ctrl-'+Key).length == 1) {
                e.preventDefault();
                if (!$('#divLoader').is(":visible"))
                    $('.ctrl-'+Key).click();
                console.log("You pressed ctrl + "+Key );
            }
        }
    });
    $(document).on('keyup', function (e) {
        if(!e.ctrlKey ){
          $('[class*="ctrl-"]').removeAttr("data-ctrl");
            $(".tooltip-ctrl").remove();
        }
    })
});
#banner-message {
  background: #fff;
  border-radius: 4px;
  padding: 20px;
  font-size: 25px;
  text-align: center;
  transition: all 0.2s;
  margin: 0 auto;
  width: 300px;
}

#banner-message.alt {
  background: #0084ff;
  color: #fff;
  margin-top: 40px;
  width: 200px;
}

#banner-message.alt button {
  background: #fff;
  color: #000;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="banner-message">
  <p>Hello World</p>
  <button class="ctrl-s" title="s">Change color</button><br/><br/>
  <span>Press CTRL+S to trigger click event of button</span>
</div>

-- or --
check out running example https://mcmap.net/q/46212/-creating-a-shortcut-keys-for-a-specific-buttons-on-the-webpage-chrome

Note: on current logic, you need to press Ctrl + Enter

Owenism answered 3/12, 2019 at 12:5 Comment(0)
B
-4

This also might help, a small JavaScript function, which works fine:

<script type="text/javascript">
function blank(a) { if(a.value == a.defaultValue) a.value = ""; }

function unblank(a) { if(a.value == "") a.value = a.defaultValue; }
</script> 
<input type="text" value="email goes here" onfocus="blank(this)" onblur="unblank(this)" />

I know this question is solved, but I just found something, which can be helpful for others.

Barbarossa answered 13/9, 2011 at 10:45 Comment(1)
The question was for triggering a button click with the enter key in a textbox. Your solution is for a "watermark" type of functionality.Pitts

© 2022 - 2024 — McMap. All rights reserved.