Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HTML Form - Execute script when pressing 'Enter', without submitting [duplicate]

Possible Duplicate:
jQuery Event Keypress: Which key was pressed?

OK, here's my situation (I've solved this issue in the past, but since I'm not sure my approach was the best, I'm all ears for some advice) :

  • I've got a simple HTML form
  • The purpose of this form is NOT to be submitted EVER
  • The user normal clicks the (pseudo)Submit button, and the desired action is executed (via Javascript/Ajax, etc)

The thing is :

  • If the user hits enter, then the form is submitted, something we definitely DON'T WANT.
  • What we want is to catch that particular keypress, and in that case, trigger the action that would normally be executed if the button was clicked.

How would you go about this?


My Approach


The Form

<form id="someId" action="#" method="post" 
      onsubmit="return false;" onkeypress="return enterSub(this,event);">
...
</form>

The Code

function enterSub(inField, e) 
{ 
        var charCode;

        if(e && e.which)
        {
            charCode = e.which;
        }
        else if (window.event)
        {
            e = window.event;
            charCode = e.keyCode;
        }

        if (charCode == 13) 
        {
            performThatAction; // My Main action
        }
 }
like image 205
Dr.Kameleon Avatar asked Aug 21 '12 05:08

Dr.Kameleon


People also ask

How do I stop form submission on Enter key?

To prevent form submission when the Enter key is pressed in React, use the preventDefault() method on the event object, e.g. event. preventDefault() . The preventDefault method prevents the browser from refreshing the page when the form is submitted.

How do you submit a form when Enter is pressed?

Given an HTML form and the task is to submit the form after clicking the 'Enter' button using jQuery. To submit the form using 'Enter' button, we will use jQuery keypress() method and to check the 'Enter' button is pressed or not, we will use 'Enter' button key code value.

How do you prevent form submit on Enter in jQuery?

$(document). on('keyup keypress', 'form input[type="text"]', function(e) { if(e. keyCode == 13) { e. preventDefault(); return false; } });

What is the default for form submission?

The HTMLFormElement. method property represents the HTTP method used to submit the <form> . Unless explicitly specified, the default method is 'get'.


1 Answers

Bind to the submit of the form rather than the click of a button, then prevent the default action.

$("#myform").submit(function(e){
    e.preventDefault();
    alert("The action has occurred without submitting the form!");
});
like image 114
Kevin B Avatar answered Sep 22 '22 16:09

Kevin B