1

Currently I can only submit my textarea by clicking on the submit button. I've also seen multiple posts, such as this one, on how submit the form by hitting Enter. However, I'd like to know if there was a way to implement both in one function.

Currently, I have: $('form[name=userForm]').on('submit', function() {...} .

Community
  • 1
  • 1
TheRealFakeNews
  • 7,512
  • 16
  • 73
  • 114
  • 3
    Think about user reaction though -- if I'm using a textarea, I don't expect it to submit on enter. I expect it to have a new line. – Sterling Archer Feb 22 '16 at 21:42

2 Answers2

1

You can call multiple event listeners in one function by separating them with a space.

In this case we're listening for both the keypress and click events, and passing in the event parameter to listen for which button was entered.

<input type="submit" id="submit-btn">Submit</button>

$(function(){
    $("#submit-btn").on("keypress click", function(event){
        var formValue = $("textarea").val();
        if (event.which === 13 || event.type === "click") {
           // Form submission code goes here
        }
    });
});

You could also do it with two functions. Inside the second one, you could ivoke the submit button's click event.

$("#submit-btn").click(function(){
    var formValue = $("textarea").val();
        // Submission logic goes here.
    })

    // Trigger the submit button's click event

    $("textarea").keypress(function(event) {
        if (event.which === 13) {
            $("#submit-btn").click();
        }
    });
Richard Hamilton
  • 25,478
  • 10
  • 60
  • 87
0

Define your submit function and reuse it:

var submitForm = function() {...};

$('form[name=userForm]').on('submit', submitForm);

$('textarea').keypress(function (e) {
  if (e.which == 13) {
    submitForm();
  }
});
jeffjenx
  • 17,041
  • 6
  • 57
  • 99