How to make “Enter” key in a textarea submit a form

前端 未结 6 907
太阳男子
太阳男子 2020-12-16 08:49

I have a chat that uses textarea instead of text for obvious reasons. This is why each time members hit ENTER they get a new line instead of sending the message. I would li

6条回答
  •  无人及你
    2020-12-16 09:34

    Vanilla JavaScript solution

    function submitOnEnter(event){
        if(event.which === 13){
            event.target.form.dispatchEvent(new Event("submit", {cancelable: true}));
            event.preventDefault(); // Prevents the addition of a new line in the text field (not needed in a lot of cases)
        }
    }
    
    document.getElementById("usermsg").addEventListener("keypress", submitOnEnter);
    

    If you would prefer to not submit if Shift is clicked all you need to do is change line 2 to:

    if(event.which === 13 && !event.shiftKey){
    

    To clear the textarea just add this inside the if statement body

    event.target.value = "";
    

    To use this with Internet Explorer 11 change line 3 to:

    var newEvent = document.createEvent("Event");
    newEvent.initEvent("submit", false, true);
    event.target.form.dispatchEvent(newEvent);
    

    But wait? Why not use event.target.form.submit();?

    When you invoke the submit method of the form the event listeners will not be called.


    Demo:

    function submitOnEnter(event){
        if(event.which === 13){
            event.target.form.dispatchEvent(new Event("submit", {cancelable: true}));
            event.preventDefault(); // Prevents the addition of a new line in the text field (not needed in a lot of cases)
        }
    }
    
    document.getElementById("usermsg").addEventListener("keypress", submitOnEnter);
    
    document.getElementById("form").addEventListener("submit", (event) => {
        event.preventDefault();
        console.log("form submitted");
    });

提交回复
热议问题