user7350806
user7350806

Reputation:

Javascript is not submitting on enter key pressed, it just clears the textbox

I have the following code:

    <form style="position: absolute; bottom: 5px; padding-bottom: 10px;height:    10%;" id="newmessageForm">
            <textarea name="message" placeholder="Type your message here"   rows="9" cols="225" id="newmessage" resize="none" style="float: left; opacity: 0.7;"></textarea>
            <input class="btn-login" type="Submit" name="send" style="float: left">
    </form>

<script>
var chatInput = document.getElementById('newmessage');
var chatForm = document.getElementById('newmessageForm');
chatInput.onkeypress = function(e) {
 if (e.charCode == 13) {
   e.preventDefault();
   chatForm.submit();
   }
};
</script>

and instead of sending the message on enter key pressed, it just clears the textbox, can someone please help?

Upvotes: 0

Views: 34

Answers (3)

Soviut
Soviut

Reputation: 91535

You don't need to listen for the enter keypress, instead listen for the form submit event and prevent the default action.

var chatForm = document.getElementById('newmessageForm');
chatForm.addEventListener('submit', function(e) {
    e.preventDefault();
});

Upvotes: 0

Jonathan Bartlett
Jonathan Bartlett

Reputation: 512

Your form doesn't do anything, it is submitting but the form does not do anything, add an action="" and method="" for it to show the submit.

Upvotes: 1

MrGrigri
MrGrigri

Reputation: 314

Where is this submitting to? There is no action attribute in the form element. You will need both the method and action attributes in order for the submit to work.

Upvotes: 1

Related Questions