Question

I need to submit the form with the enter key, but it is not like the other questions in this website in my case. I do not have a input[type="submit"], but I have a button (<button id=""></button>).

The full code of my form:

<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<script src="js/my_script.js" type="text/javascript"></script>

<form id="myForm" action="userInfo.php" method="post">
<textarea name="mesazhi" cols="35" rows="4"></textarea>
<?php $idiperdoruesit = $_SESSION['id']; ?>
<input type="hidden" name="idiperdoruesit" value="<?php echo $idiperdoruesit; ?>" />
<br /><button id="sub" style="border-radius:0px; border-size:2px; border-style:solid; border-color:#ffffff; border-width:thin; background-color:#000000; color:#ffffff; height:26px; width:60px;  font-size:16px;">Send</button>
</form>

When the user clicks the button Send, then a jquery function sends the message to the database without reloading the page. Below is the jquery function:

$("#sub").click( function() {
 $.post( $("#myForm").attr("action"), 
         $("#myForm :input").serializeArray(), 
         function(info){ $("#result").html(info); 
   });
 clearInput();
});

$("#myForm").submit( function() {
  return false; 
});

function clearInput() {
    $("#myForm :input").each( function() {
       $(this).val('');
    });
}

How can I make to send the message by pressing the enter key?

Was it helpful?

Solution 2

Use the form's submit event, the default behavior of a form is to submit either when the submit button is clicked, or the enter key is pressed on a form input.

$("#myForm").submit(function(){
    $.post( $("#myForm").attr("action"), 
         $("#myForm :input").serializeArray(), 
         function(info){ $("#result").html(info); }
    );
    clearInput();
    return false;
});

now make your button a submit button and get rid of the click event. Now, when you press enter in any input other than a textarea, the form will submit and your handler will be called. No need for keydown event handlers and click handlers.

OTHER TIPS

You can use the keydown handler to do this. The return key is key 13.

$('input').on( 'keydown', function( e ) {
  if( e.which == 13 ) {
    tickleAPolarBear();
    //or something like $('#myForm').submit();
  }
} );

See mdn for more information about the keydown event.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top