MrDysprosium
MrDysprosium

Reputation: 499

Page reloading when hitting enter on a form

Yes this question has been asked for, no the answers don't seem to be working for me.

Simply put, here's the code:

   <form id="frm1" onsubmit="preventDefault();">
  Message: <input type="text" name="message"><br>

  <input type="button" onclick="sendMessage()">
    </form>

<script>
function sendMessage() {
    var message = document.getElementById("frm1").message.value;
    socket.emit('browsermsg', {data: message})
}
$("frm1").submit(function (e) {
    e.preventDefault();
    sendMessage();
    alert("call some function here");
 });
</script>

using onsubmit="preventDefault();" doesn't have any effect, where as using "onsubmit="return false;" prevents the from from being submitted at all when enter is pressed.

I want the form to submit when enter is pressed, but then to also not reload the page. I'm failing to see where in code the page feels the need to reload when the enter key is pressed at all, I'm assuming it's something built into JS?

Upvotes: 1

Views: 48

Answers (1)

Muhammad Usman
Muhammad Usman

Reputation: 10148

$("frm1").submit(function (e) { should be $("#frm1").submit(function (e) {

As you are selecting from by Id, this is how you use the selector with id $('#Id')

Upvotes: 4

Related Questions