简体   繁体   中英

Enter key to send works only once in Javascript

I have a code that submits the form, whenever we press enter key on text area... it works, but code runs only once. Whenever I press enter again to submit it doesn't work.

Here is my Javascript code:

$('.comment_ta').on("keypress" , function(e){

    if (e.which == 13) {
       $(this).closest('form').submit();
    }

});

and here is the form and text area .. code is in ruby n haml

=form_for( ([c,c.confessioncomments.build]), remote: true ) do |f|
        .cmnt
            =f.text_area :content class: "form-control comment_ta"
        =f.submit 'Comment'     , clasS:'btn btn-default cbtn'

Now it works well for the first time but whenever I render the new form after submission it doesn't work.

Give this a shot:

$(document).on('keypress', '.comment_ta', function(e){

    if (e.which == 13) {
       $(this).closest('form').submit();
    }

});

I assume this is because the .comment_ta element gets replaced in the DOM, which means the .on event listener will no longer work. By applying the event listener to the document instead, the event listener should continue to work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM