0

I'm struggle with making this work and understand how I can call specific button by pressing Enter in Javascript.

As Example I have

$(document).ready(function () { 
    $('#myText').keyup(function () {
       alert(e.keyCode); 
    });

    $('#myButton').button().click(function () {
       alert('Button click 1!');
    });

    $('#myButton2').button().click(function () {
       alert('Button click 2!');
    });
});
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<form action="#">
<button id="myButton">Button</button>
<button id="myButton2">Button2</button>
<input type="text" id="myText" />
</form>

How to make that when I hit enter in the Mytext value It's click on myButton2 ?

DEMO: http://jsfiddle.net/WZ6TM/610/

UPDATE:

The following answers not working as expected, please see my code structure:

$(document).ready(function () {

    $('input#manualuser').keyup(function(e) {
        if (e.keyCode === 13) $('#search').click();
      });


    $('#search').click(function search() {
        if ($("input#manualuser").val() === '') {

            $('#infostatus').html("<label id='infostatus' class='info'>Please Enter Username</label>");

        }
        else {
            $.ajax({
                url: "https://" + $seldom + ":443/api/example/" + $("input#manualuser").val(),
                type: "GET",
                dataType: 'Jsonp',
                success: function (result) {....
Daniel A
  • 75
  • 10

3 Answers3

1

Problem is being that the default action of pressing Enter key (keydown event) is 'activate' the focused item (actually button1). You need to prevent defaults. And then customize your events as follow.

Here the snippet

http://jsfiddle.net/WZ6TM/637/

$(document).ready(function () { 

$('#myText').keydown (function(e) {
 if(e.which == 13) {  
e.preventDefault();
}
});

$('#myText').keyup(function (e) {
e.preventDefault();

  if(e.which == 13) {   
$("#myButton2").trigger('click');

}

});

$('#myButton').button().click(function () {
   alert('Button click 1!');
});

$('#myButton2').button().click(function () {
   alert('Button click 2!');
});
});

In the example if you close the dialog with Enter, event is launched again so take care and dont think that is doing a loop or something. It is actually working and I hope you understand what is happening.

Cheers

Sam
  • 1,459
  • 1
  • 18
  • 32
  • This works! could you please explain why is that focus on button (on keydown) and actually performing the action on keyup ? or please refer to a link or article that explains this please. Thank you for your help. – Daniel A Mar 09 '18 at 21:09
  • What I am doing is prevent default action on keydown event if the key is Enter. (Enter keydown). You know, this action by default is activate focused element of the page.. It is a default behaviour When page loads it goes to the first element, mybutton1 in your case then when u press enter the default action is made and activate the button. Doing event.preventDefault() you "deactivate" it and then u can freely customize your events. You understand? – Sam Mar 09 '18 at 22:29
0

you need to catch the form submit

$('form').submit(function(e){
  e.preventDefault();
  $('#mybutton2').click()
})

Alternatively, you could catch $('body').keyup() and do things with that.

catbadger
  • 1,662
  • 2
  • 18
  • 27
-1

I see two possibilities. The simplest would be to hook off of the submit event:

$(document).ready(function () { 
  $('form').submit(function (e) {
   e.preventDefault();
   $('#myButton2').click();
  });

  $('#myButton').click(function () {
   alert('Button click 1!');
  });

  $('#myButton2').click(function () {
   alert('Button click 2!');
  });
});

And change the mark-up so that the buttons will not submit by default:

<form action="#">
<button type="button" id="myButton">Button</button>
<button type="button" id="myButton2">Button2</button>
<input type="text" id="myText" />
</form>

The other way is to use keydown and listen for the enter key. I wouldn't suggest using this way, though, as listening for specific key codes can make your code harder to reason about.

http://jsfiddle.net/WZ6TM/644/ Edit: Fiddle provided

Malfus
  • 21
  • 1
  • 5
  • I am merely copying the poster's original format, I am making no assertion as to the validity of document.ready – Malfus Mar 12 '18 at 17:45
  • You shouldn't really be copy-pasting things. Why don't you just learn the language? –  Mar 12 '18 at 19:51
  • Why don't you go pester the accepted answer instead of mine? – Malfus Mar 13 '18 at 12:53
  • I'm not "pestering", just advising you **not** to copy/paste code from Google. –  Mar 13 '18 at 12:58
  • If you can improve a script, then why not? Why just copy it? –  Mar 13 '18 at 14:13
  • That is beyond the scope of the question. – Malfus Mar 14 '18 at 13:20
  • You could've mentioned it though. –  Mar 14 '18 at 17:28
  • You could have mentioned where the you got your document.ready recommendation. I have found no requirement -_or even suggestion_- to only use document.ready in the head element. On the contrary, I have found plenty of suggestions to always put code at the **bottom** of the body. – Malfus Mar 14 '18 at 17:34
  • Obviously, a quick Google finds quite a few of sites that mention this ([Quora Question](https://www.quora.com/jQuery-When-do-I-need-to-use-document-ready-function), [a SO question](https://stackoverflow.com/questions/14328449/when-do-you-put-javascript-in-body-when-in-head-and-when-use-doc-load) and a [TTH article](https://teamtreehouse.com/community/why-do-we-put-the-jquery-script-in-the-beginning-of-the-html-instead-of-at-the-end-near-the-body)). If you had researched this, you would've known. –  Mar 14 '18 at 19:02
  • If you had read the links you posted, you would have realized that they indicate the **opposite**. From the TTH article: `You're right, that in this case, there really is no reason to place those files in the head of the page, and could just as easily be placed before the closing body tag.` – Malfus Mar 15 '18 at 13:40
  • From the TTH article:`The main advantage of placing your scripts AFTER the html, is that the loading of scripts won't prevent the display of content -- which might make visitors feel that the site is slow and unresponsive.` –  Mar 15 '18 at 14:40
  • Which is an argument to place code at the bottom of the body, **and in no way indicates to "Only use document.ready if the script is in the head"**. – Malfus Mar 15 '18 at 21:05
  • Why are we still going on about this? If a script is in the head, then use `document.ready` as the DOM wouldn't be ready when the script is run, but if the script is at the bottom of the page, then don't use it as the DOM would be ready when the script is run. –  Mar 15 '18 at 21:09
  • Your insistence to provide disinformation is why I continue. Usage of document.ready is not restricted to the head and no source indicates to **only use it in the head**. – Malfus Mar 15 '18 at 21:12
  • Using document.ready leads to a slower page in general, and should not be used if one is looking for performance. Stack Overflow has even adopted this technique in their code (open devtools and see) for their `markup` code. If you don't want to adopt this technique, then feel free. I will no longer be replying to this thread. –  Mar 16 '18 at 03:19
  • The performance hit of document.ready is minimal in this case. Additionally, the Jquery site still uses doc.ready shorthand to no ill effect. I am glad that this conversation has reached its conclusion. – Malfus Mar 16 '18 at 17:26