Form submitting when pressing enter in Textarea

后端 未结 3 527
小鲜肉
小鲜肉 2020-12-28 23:38

I\'ve been trying various methods to get a form to submit when hitting the enter key. I know it works with an input field, but because this is going to be a comment, it nee

3条回答
  •  天命终不由人
    2020-12-29 00:03

    try this jsfiddle

    HTML:

    JS:

           $('.messageTextarea').keydown(function(event) {
        if (event.keyCode == 13) {
            $(this.form).submit()
            return false;
         }
    }).focus(function(){
        if(this.value == "Write your comment here..."){
             this.value = "";
        }
    
    }).blur(function(){
        if(this.value==""){
             this.value = "Write your comment here...";
        }
    });
    
    $("form").submit(function(){
           var name = $(this).siblings('.messageTextarea').val();
        var theid = $(this).attr('data-the_id');
        var dataString = name;
    
        $.ajax({
            dataType: 'json',
            url: "https://api.instagram.com/v1/media/"+$(this).attr('data-the_id')+"/comments?",
            type: "POST",
            data: "text="+dataString,
            success: function(data) {
                // finish load
                console.log(data, dataString, 'fail');
            },
            error: function(data) {
                var username = JSON.parse(localStorage.getItem('iguser'));
                var profilepic = JSON.parse(localStorage.getItem('iguserimg'));
                //console.log(data, dataString, 'succ');
    
                $('.box[data-the_id="' + theid + '"]').children('.postMessage').children('.messageComments').append('
  • ' + username + '
    ' + dataString + '
  • '); $('.messageTextarea').val(''); // Remove comment from TextArea } }); return false; }); ​ ​

提交回复
热议问题