v-on:submit.prevent not stopping form submission - javascript

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

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.

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"

Related

How to fill in data in an input field using Javascript directly on page load?

This question has been asked a lot it seems on Stack Overflow but none of the solutions seem to be working. I am developing a web application where I have to fill in data in data fields on page load. Here is my code:
<!DOCTYPE html>
<html>
<body>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<input type="text" id="datetime" value="" />
<script type="text/javascript">
$(document).on("pageload",function(){
//for fill field
document.getElementById("datetime").value = "here is value";
});
</script>
</body>
</html>
For some reason, when I load the page, no data gets filled in, does anyone see the reason for it?
You don't need jQuery. Try this:
<!DOCTYPE html>
<html>
<body>
<input type="text" id="datetime" value="" />
<script>
window.onload = function() {
document.getElementById('datetime').value = 'here is value';
};
</script>
</body>
</html>
What version of jquery are you using? Looks like pageload might deprecated and you should use pagecontainerload
Or better yet use the $(document).ready or .load methods?
In Jquery it's called document ready event... So use the below syntax.
$(document).ready(function(){
//for fill field
$("#datetime").val( "here is value");
});
Note the inner line of code has been changed.. This is the Jquery way of doing the same thing...
You can also use this Shorthand to $(document).ready(function(){
That is $(function(){

How can I use Javascript to handle form data & display a separate results page?

I am re-writing a large web form that is written using Perl Dancer and Template Toolkit to handle the submitted form data and display a results page. I would like to abandon Template Toolkit and Dancer in favor of a Javascript-only solution. How can I write the form to pass all of the data to Javascript and have it display the data on a nice formatted results page?
I'm unsure of what kind of data you have that could be entered in your form, so I don't have any specific help with how you could present that data in a nicely formatted way.
On the topic of passing data from a form to javascript (or jquery, since that was in your tag) here is an example of how you could accomplish this.
Let's say you have a simple form in HTML laid out something like this.
<form id="form">
<input type="text" id="input">
</form>
You can catch the submission event of this form in javascript, prevent what it would normally do, take the data from it's input fields and do something specific with them. Here's an example.
// On DOM loaded
$(document).ready(function () {
// Catch the submit event of the form
$('#form').submit(function (e) {
// Prevent default form submit event
e.preventDefault();
// Access some input field data
var input = $('#input').val();
});
});
I would be happy to point you in a more specific direction on how you could format and present your data in a nicely formatted way if you would like to provide some more information as to what data you would be passing from your form.
I figured it out! I will use HTML5 sessionStorage. Here is the code:
form html:
<html lang="en">
<head>
<meta charset="utf-8">
<title>Form test</title>
</head>
<body>
<form id='form' action="result.html" rel="external">
<input name='day' id='day' type='text'><input type='submit' id='completed' value='Completed!'>
</form>
<!-- SCRIPTS -->
<script src="jquery.js"></script>
<script src="main.js"></script>
</body>
Here is the main.js:
function saveData() {
var submit = document.getElementById('completed');
submit.onclick = function() {
sessionStorage.setItem('day', document.getElementById('day').value);
};
}
window.onload = function() {
saveData();
};
Here is the result html:
<html lang="en">
<head>
<meta charset="utf-8">
<title>Result</title>
</head>
<body>
<div id="stuff"></div>
<!-- SCRIPTS -->
<script src="jquery.js"></script>
<script src="result.js"></script>
</body>
</html>
Here is the result.js:
function displayData() {
var div = document.getElementById('stuff');
div.innerHTML = "<p>" + sessionStorage.getItem('day') + "</p>";
}
window.onload = function() {
displayData();
};

onClick event not working for button

I'm trying to show forms based on the button clicked. That is, on clicking the first button, two other buttons are displayed. However, the new buttons generated behave like dummy buttons (onClick event not working).
How can I resolve this error? Is there any alternative for this to implement the same functionality?
I have the following code:
<html>
<head>
<title>Frequently Asked Questions</title>
<link rel="stylesheet" type="text/css" href="CSSfiles/faqCSS.css">
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script >
function addContent(divName, content) {
document.getElementById(divName).innerHTML = content;
}
</script>
</head>
<body>
<p>Put banner and logo on top; Put footer later </p>
<div class="intro">
Looking for help? We provide you information about what can be done when in trouble. Hope you find it helpful!
</div>
<form name="myForm" class="select">
<input type="button" value="ND" class="select-button" onClick="addContent('myDiv', document.myForm1.ND.value);"><br>
<input type="button" value="E" class="select-button" onClick="addContent('myDiv', document.myForm1.E.value);">
</form>
<form name="myForm1" class="select">
<textarea name="ND">
<input type="button" value="Earthquakes" class="trial" onclick="addContent('yourDiv', document.myForm2.HW.value);"/><br>
</textarea>
<textarea name="E"><u>E</u></textarea>
</form>
<form name="myForm2" class="select">
<textarea name="HW">
<u>Hello world!</u>
</textarea>
</form>
<br><br>
<div id="myDiv"></div>
<div id="yourDiv"></div>
</body>
</html>
It is not clear to me how you add the buttons to your DOM (could you post that code?).
However, say that your button has an id of 'MyButton1',
<button id="MyButton1">Hello</button>
then if you do this with jQuery, your code needs to have it delegate the click, by hooking an object that is already existing and will contain your button; for example the body element:
// This is registered before MyButton1 is created.
$('body').on('click', '#MyButton1', function(event) {
alert("Hello, I'm button 1");
}
Using plain javascript, after you have created the new content (so that getElementById can find the button), you need to bind the onclick event:
document.getElementById('MyButton1').onclick = function() {
alert("Hello again");
}
or (not supported on older IEs)
document.getElementById('MyButton1').addEventListener("click",
function() {
alert("Still me");
});
Here you can find a Javascript fiddle with code re: the javascript method.
Initially keep all forms hidden. Put them in the desired division. Onclick of each button only show/hide intended form..
This can help you out.

submit form on click event using jquery

So can someone please tell why neither of these options will actually submit the form? I am trying to do something more complicated but I have boiled it down to this to try and figure out why I can't seem to get this form to submit using a click event and submit()
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$('#submitButton').click(function(e) {
e.preventDefault();
$("#testForm").submit();
});
$('#submitLink').click(function(e) {
e.preventDefault();
$("#testForm").submit();
});
});
</script>
</head>
<body>
<form action="javascript:alert('submitted');" method="post" id="testForm">
<label>Name</label>
<input type="text" name="name" value="" />
<input type="submit" name="submit" value="Submit" id="submitButton" />
<p>Submit Form</p>
</form>
</body>
</html>
Thank you!
it's because the name of the submit button is named "submit", change it to anything but "submit", try "submitme" and retry it. It should then work.
Why not simply use the submit button to run the code you want. If your function returns false, it will cancel the submission.
$("#testForm").submit(function() {
/* Do Something */
return false;
});
If you have a form action and an input type="submit" inside form tags, it's going to submit the old fashioned way and basically refresh the page. When doing AJAX type transactions this isn't the desired effect you are after.
Remove the action. Or remove the form altogether, though in cases it does come in handy to serialize to cut your workload. If the form tags remain, move the button outside the form tags, or alternatively make it a link with an onclick or click handler as opposed to an input button. Jquery UI Buttons works great in this case because you can mimic an input button with an a tag element.
Using jQuery button click
$('#button_id').on('click',function(){
$('#form_id').submit();
});
Do you need to post the the form to an URL or do you only need to detect the submit-event? Because you can detect the submit-event by adding onsubmit="javascript:alert('I do also submit');"
<form action="javascript:alert('submitted');" method="post" id="testForm" onsubmit="javascript:alert('I do also submit');">...</form>
Not sure that this is what you are looking for though.

jQuery forms submit

I create this tiny JS so i can control the form submit with jQuery
$('#submit').click(function() {
$('#addForm').submit();
});
Can I use a simple href link for it?
Something like
link
I tried
link
but it didn't work (it by pass the other jQuery in the page)
If you want the JS that you created to control the submit, don't have a href value in your link:
<a id="submit">link</a>
You cannot submit your form that way with a link and some javaScript, even jQuery. You have to use an XHR call to submit your query AND not refresh the page. (you can submit your form with a link as presented by Dan, but I understand that you want to do more than just that from your questions)
The reason being that the "return false" statement will impact the link action, and not the form submission itself.
In any case, I would advise you to not use a link to submit your form at all.
You can easily submit a form with the normal submit button and a bit of jQuery. That way, you provide a nice fallback to your users that have not enabled javaScript.
You can even submit the form with some client side validation, using the following HTML / javaScript:
<!DOCTYPE html>
<html>
<head>
<title>Sample</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('#addForm').submit(function(){
validate();
ajax_submit_function_taking_form_data_as_argument($(this).serialize());
return false;
});
});
function validate(){
//Do some client side validation if required
}
function ajax_submit_function_taking_form_data_as_argument(theData){
$.ajax({
type: 'GET',
url: "http://search.google.com/",
data: theData,
error: function(e){
alert('error...');
},
success: function(data){
alert('success!');
}
});
}
</script>
<style type="text/css"></style>
</head>
<body>
<form id="addForm">
<input type="text" name="field1" value="" />
<input type="submit" value="submit" />
</form>
</body>
</html>
A last solution, albeit maybe too heavy weight for your use, would be to use the excellent jQuery form plugin from http://jquery.malsup.com/form/
I hope that helps!
You can attach to the click event with jquery. It's also cleaner not to put any javascript in your html.
<!DOCTYPE html>
<html>
<head>
<title>Sample</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('#aSubmit').click(function(){
$('#form1').submit();
return false;
});
});
</script>
<style type="text/css"></style>
</head>
<body>
<form id="form1" action="http://www.google.com/search" name=f>
<input name="q" />
</form>
submit
</body>
</html>
Never ever put JavaScript in the href attribute. If you must put in the HTML, use the onclick attribute, and remember to add return false. Also, never ever prefix script with javascript:.
Your first script block should do the job just as fine as well, though.
(And what does "it by pass the other jQuery in the page" mean?)

Categories

Resources