3

I would like to ask why it will have multiple response? How can i enter the input field with just one response?

Expectation : Input the data in input field and press the enter , it will execute the actions.

$("#textInput").keypress(function (e) {

  console.log("123");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>

<input type='text' id='textInput'/>
csharpbd
  • 3,786
  • 4
  • 23
  • 32
Lamp Chan
  • 31
  • 1

4 Answers4

3

You have syntax error in you code. closing should be }); instead of )};

$("#textInput").keypress(function (e) {
     if(e.which == 13) {
        alert('You pressed enter!');
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="textInput">
Dinesh undefined
  • 5,490
  • 2
  • 19
  • 40
0

The keypress event is sent to an element when the browser registers keyboard input.

— jQuery Documentation link

What you really want is .submit() as they are the one that will only be triggered when the user submits info.

$("#textInput").submit(function (e) {

console.log("123");
)};

Or if you only want to detect enter keypress but not submit, use this:
How to detect pressing Enter on keyboard using jQuery?

Pang
  • 9,564
  • 146
  • 81
  • 122
Dreamer
  • 171
  • 3
  • 10
0

I think, you should have choose other event,like onblur to fix your problem

$("#textInput").on('blur',function (e) {

  console.log("123");
)};

In your code ,keypress events gives you output,in every keypress action,So this is the reason you got multiple responses

And next,if you think,if you want to press Enter button then need response,In this case little changes will helps you

    $("#textInput").keypress(function (e) {
     if(e.which == 13) {
        console.log("123");
    }


});
ubm
  • 636
  • 11
  • 21
0

Expectation : Input the data in input field and press the enter , it will execute the actions.

In order to submit the corresponding form as soon as the user enters a text string and a final enter key you can:

  • test if current char is the enter key (e.which == 13)
  • get the closest form
  • submit the form

$("#textInput").on('keypress', function (e) {
    if (e.which == 13) {
        $(this).closest('form').submit();
    }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<form action="/action_page.php">
    Enter text and type enter to submit:<br>
    <input type="text" name="textInput" value="">
</form>
gaetanoM
  • 41,594
  • 6
  • 42
  • 61