jmbockhorst
jmbockhorst

Reputation: 88

Submiting a form with jquery

I am trying to submit this form when the Enter key in the textarea is pressed. It seems like it should work, but it doesn't. I get the alert, and It refreshes the page, but it doesn't submit the form. Whats wrong with it? thanks! Just to clarify, I want pressing the enter key to do the exact same thing as hitting the submit button.

<?php
//Doing stuff with the submitted form
?>

<form id='myform' action='' method='post'>
        <tr>
            <td><textarea id='but' class='messin' name='mess'    placeholder='Reply...'></textarea></td>
            <td><input class='messin' type='submit' name='submit'   value='Send'/></td>
        </tr>
    </form>
    <script type="text/javascript">
        $(document).ready(function(){
        $("#but").keyup(function(event) {

        if (event.which == 13) {
        event.preventDefault();
        alert("Submit!");

        $("#myform").submit();
        location.reload();
        }
        }); 
        });
</script>

Upvotes: 0

Views: 55

Answers (3)

Sharikov Vladislav
Sharikov Vladislav

Reputation: 7269

$('#but').keypress(function (event) {
  if (event.which == 13) {
    $('#myform').submit();
  }
});

Hope this code will help you.

ADD If you don't want to send form use event.preventDefault(); or return false;. Look this example:

$('#but').keypress(function (event) {
  if (event.which == 13) {
    $('#myform').submit(
     // do some stuff with form
     event.PreventDefault(); // or return false; // return false == event.PreventDefault()
    );
  }
});

Upvotes: 0

Ankur Aggarwal
Ankur Aggarwal

Reputation: 3101

You are using same id for both the form elements. Id's should be unique in nature. You can use class instead

 <td><textarea class='messin' name='mess'    placeholder='Reply...'></textarea></td>
 <td><input class='messin' type='submit' name='submit'   value='Send'/></td>

JS Change:

$(".messin").keyup(function(event) {

//code
});

Upvotes: 0

Luis Masuelli
Luis Masuelli

Reputation: 12333

Remember that .submit() is not a blocking operation. This means that if you call something after which causes a navigation modification, you will abort your submission. Try not reloading the page.

BTW submission means always a (synchronous) redirection. If your intention is to submit an AJAX form (which will not automatically redirect), you should do the reload in the complete callback of the ajax call.

Upvotes: 1

Related Questions