skip to Main Content

I have a textArea where you type a message, and to submit it you have to press a button.
The whole submitting process will be in JS/jQuery. For now the submission will be triggered only by the onclick event of the submit button.

$(".btn-success").click(function () {
        // Submit Code
 });

Now I want to combine :

$('textarea').keypress(function (e) {
        if(e.which == 13) {
            // Same Submit Code
        }
    });

So that when the user presses ‘enter’, the message is submited, without having to repeat the function twice.

Any help ? Couldn’t find anything on the forum…

3

Answers


  1. the function was born to do it give it a name:

    function onSubmit() {
      // Submit Code
    }
    
    $(".btn-success").click(onSubmit)
    $('textarea').keypress(function (e) {
      if(e.which == 13) {
        onSubmit()
      }
    });
    

    if in function onSubmit use this please replace with $(".btn-success")[0]

    Login or Signup to reply.
  2. Simply use a standard named function:

    $(".btn-success").click(doIt);
    $('textarea').keypress(function (e) {
            if(e.which == 13) doIt();
        });
    
    function doIt() {
    // can be called from anywhere
    }
    
    Login or Signup to reply.
  3. if the functions were exactly the same end the events occure on same element I was going to recommend joining them with on:

    $('#element').on('click change other_events', function(e){...});
    

    Yet, as this is not the case, The Simple Answer is Creating a submit function and calling it in the different events callbacks

    function submit() {
        // your code
    }
    $(".btn-success").click(function () {
        submit()
    });
    $('textarea').keypress(function (e) {
        if(e.which == 13) {
            submit()
        }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search