0

Html Code :

    <input type="text" id="normal_input" />
    <button class="normal_button">Button</button>
    

Js Code :

    $('.normal_button').click(function(e){
       console.log(e);
    });
    

The function works good when I click the button
however when I press enter in the input text, it also trigger the button click function.
I solved this by change button element to input button
but I'm still curios about the reason
is it some kind of jquery bug or something is wrong?

0

4 Answers 4

1

By default, unless you specify any actions for the <button> element, it would act like a submit button. Basically submit button will get fired when you press enter from its parent form's input control

Sign up to request clarification or add additional context in comments.

Comments

1

A button inside of a form by default acts like a submit input. So when you hit enter, it triggers the function.

Comments

1

The default behaviour of a <button> is to submit. If you add type="button" it will act as a normal button.

Comments

0

Its not a bug. Its the default behaviour of a input field on enter. Or on click of a button element with type=submit or a input type=image in a form.

If you wish to avoid submit of your form on press of enter on your input fields. try the code below:

HTML

<form>
<input name="ip" type="text" class="dont_submit" id="normal_input" />
    <input type="button" class="normal_button" value="button"/>
</form>

Script

<script>

    $('.dont_submit').keydown(function(ev){
        console.log(ev.which);
        if (ev.which === 13) {            
            ev.preventDefault();
        }
    });

</script>

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.