In my HTML I've got a form without an onsubmit event listener:
<form action="contact.php" method="post" id="contact">
...
<input type="submit" value="Send" />
</form>
As a result, the form is always posted whenever I click the "Send" button. However, I'd like to validate the input first, so I'd like to attach an event listener and intercept the post. This is how I attach the event listener to the form:
window.onload = function() {
function validate() {
return window.confirm("Confirm");
}
var form = document.getElementById("contact");
form.addEventListener("submit", validate);
}
While the event listener is being executed, if I go by above approach the form is always posted! However, if I make the validate() function global and use onsubmit="return validate();" in the <form> tag, then the form is only being submitted conditionally, as expected.
Why does this not work by adding the validate() function as above? It seems the false return value gets lost?
Modern event handling has a more complex API, it gives more flexibility but that comes at the cost of not being able to tie behaviour to a simple boolean result.
For your use case, you need to capture the event object:
function validate(ev) {
Then you can prevent the default action on it:
if (!confirm('Confirm')) {
ev.preventDefault();
}
Related
I'm using D3. I have click-handling code for an input to stop form submission and do some validation. Then if validation succeeds, I want to submit the form.
How do I submit the form programmatically, using D3 selectors? form.submit() says the submit method does not exist. (I'm confident that form is the form element.)
I'm also trying form.dispatch('submit') but that does not work either:
import { select as $, event as d3_event } from "d3";
$(el).on("click", function() {
// prevent form submission
d3_event.stopPropagation();
d3_event.preventDefault();
// later, submit form?
var form = $(this.parentNode);
form.dispatch('submit');
}
My HTML:
<form method="post" action="myaction">
<button class="create-new btn popup"><i class="fa fa-external-link"></i> Submit</button>
</form>
I don't see a submit event in the predefined list of events for a d3 node. Here's an approach that fires the submit event by selecting the DOM node using node() function. (Btw I'm not using imports here)
d3.select('#submit').on('click', function() {
// prevent form submission
d3.event.stopPropagation();
d3.event.preventDefault();
// later, submit form?
var form = d3.select(this.parentNode).node();
form.submit();
})
<script src="https://d3js.org/d3.v4.js"></script>
<form id="myform" action="submit-form.php">
Search: <input type='text' name='query'>
Submit
</form>
Another approach I can think of as of now is define a custom event listener for submit and dispatch it which would still look for the DOM node in the listener function. (i.e. basically calling <form>'s built-in submit() function.
Lets say I have this form
<form onsubmit="submitData();">
<input type="text" pattern="^[A-z]+$" required>
<button type="submit">OK</button>
</form>
Upon clicking the submit button, I don't want the form to post any data in the address bar or navigate anywhere, I just want it to run the submitData function and thats it. The reason I want to use the form is because of its validating functionality (it wont let you submit if the input text is missing or doesn't match the pattern).
If I switch the value of onsubmit on the form to "return false;" then it won't navigate but "submitData(); return false;" doesn't work. Any other ideas?
Try adding e.preventDefault(); at the beginning of your code, with the event being passed to your function submitData(e) {, like this:
function submitData(e) {
e.preventDefault();
...
}
See: https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault
Just add event.preventDefault that is automatically pass by the form to the function:
function submitData(event){
event.preventDefault();
//your code will be here
}
read more : https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault
Use event.preventDefault().
Learn more: https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault
add this to your code:
document.getElementById("addYourTagHERE").addEventListener("onsubmit", function(event){
event.preventDefault()
});
or this in your function:
function submitData(event) {
event.preventDefault();
}
You'd want to cancel the default action of the submit event handler, so:
function submitData() {
// whatever logic you have...
return false;
}
I believe this works too:
function submitData( e ) {
e.preventDefault();
// whatever logic you have...
}
I have a simple HTML form:
<form name="form" id="form" method="post" action="">
<label for="input_text"><span>Input Text:</span></label>
<input type="text" name="input_text" />
<input type="submit" name="submit" value="Submit" />
</form>
Then I prevent the default click action, because I want to use AJAX to handle the submission instead of the regular method.
// prevent page refresh
var form = document.getElementById('form');
function stopDefault(event) {
event.preventDefault();
}
form.addEventListener('click', stopDefault, false);
However this causes some unexpected behaviour.
If I get the submit button and make an anonymous onclick function for it, the onclick function will fire even if the form is submitted by hitting enter when the cursor is inside a form field, i.e. it will also fire by not clicking on submit. Here's an example:
var button = form.submit;
button.onclick = function() {
console.log('clicked');
}
Strangely enough this onclick function will also catch non-click form submissions. On the other hand, if I try to catch an actual form submission...
form.onsubmit = function() {
console.log("submitted");
}
...it won't fire!
Why is that?
To me it seems more logical to handle form input onsubmit rather than onclick, but I guess that just isn't how it works.
Also, as a side note, interestingly it doesn't matter whether the target event for the preventDefault() method is the actual form or the submit button.
To prevent page refresh you just need this
// prevent page refresh
var form = document.getElementById('form');
form.onsubmit = function() {
console.log("submitted");
return false; // this prevents page refresh
}
FIDDLE
I'm trying to use a form validator from ink.sapo.pt http://ink.sapo.pt/index.php/js/ui#formvalidator
I want to intercept the submit event to write my own code but the following event is always called:
$("#myform").submit(function() {
alert('Handler for .submit() called.');
});
even if the onsubmit attribute is false.
Basically I want ink.sapo.pt to validate my form but I want to use my own code every time the form is validated.
Pure java-script
<form id="myform" class="ink-form block" method="post" action="#"
onsubmit="submitForm(this);">
function submitForm(formObj)
{
if(SAPO.Ink.FormValidator.validate(formObj))
{
//Button Action
}
}
Try this:
$("#myform").submit(function(ev) {
ev.preventDefault();
alert('Handler for .submit() called.');
});
Basically, what the added line is doing is, as you can guess, avoiding the default behavior on the specified event.
I have function that submitted two forms at once. And last (the second) post method does not take effect without alert().
Could you please show me my mistake.
function formFunction() {
...
$.post($("#form1").attr("action"), $("#form1").serialize() );
$.post($("#form2").attr("action"), $("#form2").serialize() );
//alert('done');
}
UPD
this is how function is calling
<form id="form0" name="form0" onsubmit="formFunction()">
<input id="mainFormValue" type="text">
The reason why it is failing is you are not cancelling the original form submission. That means the page is posting back to the server when you click the button. What you need to do is prevent that origial form submission from completing.
If you are adding the event handler with jQuery, you can use preventDefault() to cancel the form submission.
function formFunction(e) {
e.preventDefault();
$.post($("#form1").attr("action"), $("#form1").serialize() );
$.post($("#form2").attr("action"), $("#form2").serialize() );
}
Change the form submission to unobtrusive JavaScript to get the correct event object set by jQuery.
$("#form0").submit(formFunction);
The other solutions is add a return false to the submisison. Just ignore the preventDefault line I suggested above. [bad idea, but will work]
<form id="form0" name="form0" onsubmit="formFunction(); return false">