3

I have an Jquery submit textarea, now I want to set textarea submit without button submit. Just using enter key.

<textarea id="ctextarea"></textarea>

Here it's the JS :

$('.comment_button').live("click",function() 
{
    var ID = $(this).attr("id");
    var uid = $("#uid").val();
    var comment= $("#ctextarea"+ID).val();
    var dataString = 'comment='+ comment + '&msg_id=' + ID + '&uid=' + uid;

    if(comment=='')
    {
    $('#ctextarea').html("").fadeIn('slow');
    $("#ctextarea"+ID).focus();
    }
    else if (!$.trim($("#ctextarea"+ID).val()))
    {
        $("#ctextarea"+ID).focus();
    }
    else
    {
    $.ajax({
    type: "POST",
    url: "comment_ajax.php",
    data: dataString,
    cache: false,
    success: function(html){
    $("#commentload"+ID).append(html);
    $("#ctextarea"+ID).val('');
    $("#ctextarea"+ID).focus();
     }
 });
}
return false;
});

I already search the tutorials and found, but I confused where can I put the code in My JS code.

Someone can give the idea ? Thanks for helps.

Viral Shah
  • 2,263
  • 5
  • 21
  • 36
Nagini
  • 125
  • 1
  • 7

2 Answers2

3
$('#ctextarea').on('keyup', function(e){
    if(e.which == 13 || e.keyCode == 13){
        //enter key pressed.. 
    }
});
Ohgodwhy
  • 49,779
  • 11
  • 80
  • 110
0

You can subscribe to a keydown/keyup event and submit the form inside the event handler:

var KEY_ENTER = 13;
$('#ctextarea').keyup(function (event) {
    if (event.keyCode === KEY_ENTER) {
        $('form').submit();
        // Or perform any necessary ajax calls here
    }
});
Konstantin Dinev
  • 34,219
  • 14
  • 75
  • 100