1

I'm trying to have the enter key perform the same task as when a user clicks the button (see jquery). However, when I tried "keyup" and other event handlers, I couldn't get it working correctly. Any ideas on the simpliest way to do this?

Thanks for your patience, and help.

See fiddle: https://jsfiddle.net/LightYearsAway/qg8f3q37/3/

HTML

<h3>Needs</h3>
<input type="text" id="need-input" placeholder="enter text">
<button id="btn1">Need it!</button>
<ul id="need-list">
    <li>a</li>
    <li>b</li>
    <li>c</li>
    <li>d</li>
    <li>e</li>
</ul>

JS

$(document).ready(function(){

  // click button, add to list

  $("#btn1").click(function(){
      $("#need-list").append($("<li>", { text: $("#need-input").val()
      }));
  });

  // click list item to hide

  $('ul').on('click', 'li', function(event) {
      $(this).slideUp();
  });

});
Huangism
  • 16,278
  • 7
  • 48
  • 74
Steran
  • 27
  • 4

3 Answers3

0

Try this:

$("#need-input").on("keydown", function(e) { 
    if(e.keyCode == 13)
        $("#btn1").click() 
});

https://jsfiddle.net/qg8f3q37/4/

Hanlet Escaño
  • 17,114
  • 8
  • 52
  • 75
  • This is a duplicate answer. Rather than answering and creating dupliactes on SO, you need to point him to the duplicate sources. – CodeGodie Mar 16 '15 at 20:37
  • Wow! Short and simple. Any ideas on how to clear the text area so the user wouldn't have to delete each entry? (Just curious...) – Steran Mar 16 '15 at 20:38
  • @Steran simply do `$(this).val('');` after, inside the if statement. https://jsfiddle.net/qg8f3q37/5/ – Hanlet Escaño Mar 17 '15 at 00:03
-1

I BELIEVE THIS COULD HELP YOU

How to detect pressing Enter on keyboard using jQuery?

Community
  • 1
  • 1
  • This is a duplicate answer. Rather than answering and creating dupliactes on SO, you need to point him to the duplicate sources – CodeGodie Mar 16 '15 at 20:37
-1
$("#need-input").keyup(function (e) {
    var code = e.which; // recommended to use e.which, it's normalized across browsers
    if (code == 13) e.preventDefault();
    if (code == 32 || code == 13 || code == 188 || code == 186) {
        $("#need-list").append($("<li>", {
            text: $("#need-input").val()
        }));
    }
});

From answer: (jQuery - keydown / keypress /keyup ENTERKEY detection?)

acupofjose
  • 2,159
  • 1
  • 22
  • 40
  • This is a duplicate answer. Rather than answering and creating dupliactes on SO, you need to point him to the duplicate sources – CodeGodie Mar 16 '15 at 20:37