3

    <form onsubmit="myFunction()">
        Enter name: <input type="text" name="fname">
        <!--input type="submit" value="Submit"-->
        <button onclick="alert('button click')">click</button>
    </form>

press enter on input triggers button onclick, form is submitted. How to avoid button onclick trigger.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • This is a standard feature on all browsers. Enter in a form = submit. – freedomn-m Aug 25 '22 at 09:00
  • Does this answer your question? [Prevent users from submitting a form by hitting Enter](https://stackoverflow.com/questions/895171/prevent-users-from-submitting-a-form-by-hitting-enter) – freedomn-m Aug 25 '22 at 09:04
  • form onsubmit function will execute. but how onclick on button inside the form. is getting executed. any hack to avoid this. – shanmukh mullapudi Aug 25 '22 at 09:24
  • It submits by "clicking" the submit button related to the form. If you change the button to `type='button'` it won't be clicked, but then won't submit so your button click then also needs to submit the form. – freedomn-m Aug 25 '22 at 09:28

3 Answers3

6

When you have a button in a form, it defaults to type "submit" which means the first button in a form will have its onclick event triggered by the ENTER key. To prevent this from happening, simply assign type="button" to the button, and enter key will no longer affect it.

akm elias
  • 143
  • 6
0

run this after the form has been rendered

document.querySelector('input[name="fname"]').onkeydown=e=>{

   if(e.key==='Enter')e.preventDefault();

   //if you want form submission
   document.querySelector('form').submit();

};
0

try this

<form onsubmit="myFunction()">
    Enter name: <input type="text" name="fname" id="fname">
    <!--input type="submit" value="Submit"-->
    <button onclick="alert('button click')" id="btn">click</button>
</form>

<script type="text/javascript">
    var input = document.getElementById("fname");
    input.addEventListener("keypress", function(event) {
        if (event.key === "Enter") {
            event.preventDefault();
            document.getElementById("btn").click();
        }
    });
</script>
masud_moni
  • 1,121
  • 16
  • 33
Danz
  • 252
  • 1
  • 8
  • keypress is deprecated [Element: keypress event](https://developer.mozilla.org/en-US/docs/Web/API/Element/keypress_event] use 'keydown' instead [](https://developer.mozilla.org/en-US/docs/Web/API/Element/keydown_event) – matt richards Aug 25 '22 at 12:09