Joel
Joel

Reputation: 6107

Submitting form with enter

Is there anyway I can submit a form without a submit button, but only when the user press the Enter button? Kind of like when commenting on Facebook, you have the TEXTAREA but no submit button. Once you press enter the form submitted with Ajax.

Thanks,

Joel

Upvotes: 4

Views: 629

Answers (2)

Harmen
Harmen

Reputation: 22456

Set an onkeyup or onkeydown event on your textarea, the latter is better because it fires before the new line is added to the textarea

var $form = $( '#yourForm' );

$( '#yourTextArea' ).keydown(function( e ){
    if( e.keyCode == 13 ){
        $form.submit();
    }
});

$form.submit(function(){
    alert( 'submitted' );
    return false;
});

Upvotes: 4

Evan Mulawski
Evan Mulawski

Reputation: 55354

The function below checks if the keycode is 13, or the Enter key. If it is, the function calls the submitformnow function.

<script type="text/javascript">
function submitform(myfield, e)
{
var keycode;
if (window.event) keycode = window.event.keyCode;
else if (e) keycode = e.which;
else return true;
if (keycode == 13)
{   
    submitformnow();
    return false;
}
else return true;
}
function submitformnow(){document.myform.submit();}
</script>

Then, in your textarea, place onkeypress="return submitform(this, event)".

Upvotes: 0

Related Questions