0

I am trying to call jquery's preventDefault() but when I submit the form..it shows the default behaviour and the page gets reloaded.

index.html--

<body>
<script src="/socket.io/socket.io.js"></script>
<script src="/js/jquery.min.js"></script>
<script src="/js/script.js"></script>
<p>Welcome to the chat app!</p>

<ol id="messages"></ol>

<form id="message-form">
  <input type="text" name="message" placeholder="Message"/><br>
  <button>Send</button>
</form>

</body>

script.js---

jQuery('#message-form').on('submit',function(e){
e.preventDefault();
socket.emit('createMessage',{
From:'User',
Text:jQuery('[name=message]').val()
});
return false;
});

2 Answers2

-1

If you have a look at the W3C specification, it would seem obvious thing to try to mark your button elements with type='button' when you don't want them to submit.

A button element with no type attribute specified in form represents the same thing as a button element with its type attribute set to "submit"

You should make your button type as "button" and try the code. It should not reload the page.

nircraft
  • 6,513
  • 3
  • 25
  • 42
  • No. Then the submit event won't trigger on the form. You need a submit button for that to occur – charlietfl Nov 11 '18 at 15:15
  • It will still trigger, we have a click event attached in the script so that function will be triggered and you can submit the form there. – nircraft Nov 11 '18 at 15:24
  • Right now since the button acts as a submit type the jQuery('#message-form').on('submit',function(e){..} will not even be in picture since page reloads – nircraft Nov 11 '18 at 15:25
  • No you are understanding it wrong. A submit button will trigger the submit event that OP is listening to. A `type="button"` also prevents user submitting by hitting enter key on keyboard. the preventDefault() stops the default submit process – charlietfl Nov 11 '18 at 15:26
-1

Change that button element completely with <input type="submit" value="Send."/> and see if that'll work.

Momondo
  • 166
  • 1
  • 9