I'm quite new to Vue and this will be my second dummy project in efforts to learn more about it.
I currently have a form and I am trying to prevent form submission, according to the docs I can do this with v-on:submit.prevent
.
I have added this into my form tag, but when submitting the form it is still going through and is not being prevented at all.
I am using Vue version 2.1.3 and below is what I have so far:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Node JS Server</title>
</head>
<body id="chat">
<form v-on:submit.prevent="send">
<input>
<button>Send</button>
</form>
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.6.0/socket.io.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.3/vue.min.js"></script>
<script>
var socket = io();
new Vue({
el: '#chat',
methods: {
send: function(e) {
alert('Send method!');
}
}
})
</script>
</body>
</html>
What am I doing wrong? As far as I can see from the docs, the form should not submit.
Edit
Here's a fiddle with the code in it
To stop this behaviour, all we have to do is to call the preventDefault () method on the click event object. The other way we can achieve preventing the default form submission behaviour is by attaching a submit event with the prevent modifier to the starting form tag in the template.
The other way we can achieve preventing the default form submission behaviour is by attaching a submit event with the prevent modifier to the starting form tag in the template. This will prevent the page from reloading when the submit button is pressed as well.
Prevent HTML <form> from being submitted with JavaScript/jQuery This post will discuss how to prevent an HTML form from being submitted in JavaScript and jQuery. The simplest solution to prevent the form submission is to return false on submit event handler defined using the onsubmitproperty in the HTML <form> element.
The submit type will trigger the form to submit, and the submit.prevent will prevent the default submit behavior and execute myFunction as desired. This has the additional benefit of triggering form validation for required input fields!
This is a strange, but standard-compliant behaviour: If a form only contains one input, it will always submit, and preventDefault()
will not prevent that.
See here: Why does a FORM with one text INPUT submit on enter while one with two text INPUTs does not?
Solution: add annother input with type="hidden"
Here is the working fiddle: https://jsfiddle.net/xje4r1u8/2/
You need to make following changes in HTML:
<div id="chat">
<form v-on:submit.prevent="send">
<input>
<button>Send</button>
</form>
</div>
in your HTML, you had <body id="chat">
which was causing problem, replacing this with div
solved the problem.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With