0

How to press enter in input type text call function javascript by not submit form ?

When fill data into input type text and press enter keyboard i want only to call function detect_enter_keyboard(event) by not to submit form.

How can i do that ?

https://jsfiddle.net/atuyx7qc/

<form>
<input type="text" name="user" onkeypress="detect_enter_keyboard(event)">
<input name="btnLogin" onclick="test_fn();" type="button" value="Send">
</form>

<script>
function detect_enter_keyboard(event) {
    var key_board_keycode = event.which || event.keyCode;
    if(key_board_keycode == 13)
    {
        test_fn();
    }
}
</script>

<script>
function test_fn(){
alert("555555");
}
</script>

2 Answers 2

2

With preventDefault(). Add this line after if(key_board_keycode == 13):

event.preventDefault();
Sign up to request clarification or add additional context in comments.

2 Comments

by this way, I can not fill data into input.
@mongmongmongseesee Right, then you need to place the preventDefault() right after detecting if the pressed key is enter. I updated the answer.
1

use this

function detect_enter_keyboard(event) {

    var key_board_keycode = event.which || event.keyCode;
    if(key_board_keycode == 13)
    {
        event.preventDefault();
        test_fn();
    }
}
function test_fn(){
    alert("555555");
}
<form >
<input type="text" name="user" onkeypress="detect_enter_keyboard(event)">
<input name="btnLogin" onclick="test_fn();" type="button" value="Send">
</form>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.