luhuiya
luhuiya

Reputation: 2211

Jquery trigger by input instead of button

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?

Upvotes: 0

Views: 83

Answers (4)

Manpreet Didwal
Manpreet Didwal

Reputation: 86

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>

Upvotes: 0

haxtbh
haxtbh

Reputation: 3534

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

Upvotes: 1

Sterling Archer
Sterling Archer

Reputation: 22395

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

Upvotes: 1

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

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

Upvotes: 1

Related Questions