Problems with multiple javascript entries
I would like to ask why he will have multiple answers? How can I enter an input field with only one answer?
Waiting: Enter data in the input field and press enter key, it will perform 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'/>
source to share
You have a syntax error in your code. closure should be });
instead)};
$("#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">
source to share
A keypress event is dispatched to an element when the browser registers keyboard input.
- jQuery documentation link
What you really want is .submit()
as they only fire when the user submits information.
$("#textInput").submit(function (e) {
console.log("123");
)};
Or, if you only want to type input, not submit, use this:
How to detect when Enter is pressed on the keyboard using jQuery?
source to share
I think you need to select another event, for example onblur
to fix your problem.
$("#textInput").on('blur',function (e) {
console.log("123");
)};
In your code, events keypress
give you a result on every keystroke action. So you got multiple answers
And further, if you think that if you want to press a button Enter
, then you need an answer. In this case, small changes will help you
$("#textInput").keypress(function (e) {
if(e.which == 13) {
console.log("123");
}
});
source to share
Waiting: Enter data in the input field and press enter key, it will perform actions.
To submit the appropriate form as soon as the user enters the text string and the final input key, you can:
$("#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>
source to share