Simple function onSubmit? - javascript

I'm trying to call a simple function onsubmit. I tried using onsubmit and also a listener with jQuery. My problem is that when the user presses enter he gets redirected to mysite.com?
<form id="teleport">
<input id="tInput" type="text" value="Type a location" />
<input type="button" id="tSubmit" value="Submit"/>
</form>
$("#teleport").submit(function () {
teleport(document.getElementById('tInput').value);
});
How do I prevent anything from happening when submitting? Also .submit() is only detecting the enter key, how do I listen for both enter key and clicks on the submit button?

You need to prevent the default action of the form. You can do that with event.preventDefault():
$("#teleport").submit(function (e) {
e.preventDefault();
teleport(document.getElementById('tInput').value);
});
Alternatively, you could return false inside the submit event handler for the same effect.
The easiest way to make the button submit the form too will be to change it's type to submit:
<input type="submit" id="tSubmit" value="Submit" />
Or you could attach a click event handler to your current button and trigger the submit event of the form.

Prevent submiting a form:
$("#teleport").submit(function (e) {
teleport(document.getElementById('tInput').value);
e.preventDefault();
});
Submit event catches any way of submitting a form - both with clicking the submit button and enter key press.

Related

How do I know what caused a form submission?

<form name="myForm" id="a" action="/action_page.php" method="post">
Name: <input type="email" name="fname">
</form>
<button type="submit" form="a" >submits</button>
<script>
const form=document.querySelector('form');
form.addEventListener('submit',function(e){
e.preventDefault();
console.log('a',e.currentTarget);
console.log(e.target);
},true);
</script>
e.target is 'form' itself on clicking on the button whereas according to what I have understood it should be button.
I checked for other events like invalid and click,it works perfectly fine.
Is it because of some submitter?
You aren't listening to the click event of the button, you are listening to the submit event of the form, that's why you see the form as target of the Event.
The submit event is not necessarily emitted on the submit button click, it could also be emitted by pressing ↲ in a form input field (but not on a programmatic submission: see HTMLFormElement.submit())
Luckily, what caused the form submission is available in the SubmitEvent.submitter property:
document.querySelector('form').addEventListener('submit', e => {
console.log(e.submitter);
e.preventDefault();
});
<form>
<input placeholder="Type Enter here!">
<button>Submit</button>
<button>Just another submit button</button>
</form>

How to prevent form submission when invoked by HTMLFormElement.submit() [duplicate]

I am replacing some jquery codes with vanilla js, and I am having trouble with the form submit event listener
<!-- html -->
<form name="myForm">
<input type="text" name="name" />
<button type="button">Click me</button>
</form>
/* jquery code that works */
$myForm = $("form[name=myForm]")
$("form button").on("click", function(e){
$myForm.submit()
})
$myForm.on("submit", function(e){
e.preventDefault()
console.log("Submitting form")
})
/* vanilla js replacement */
myForm = document.querySelector("form[name=myForm]")
myForm.querySelector("button").addEventListener('click', function(){
myForm.submit()
})
myForm.addEventListener('submit',function(e){
e.preventDefault()
console.log("Submitting form")
})
In the vanilla js, the form submit event listener does not seem to be triggered when the form is submitted programmatically. How do I fix this?
A form's submit event listener won't be triggered when you use the .submit() method on the HTMLFormElement:
The submit event fires when the user clicks a submit button (
or <input type="submit">) or presses Enter while editing a field (e.g.
<input type="text">) in a form. The event is not sent to the form when
calling the form.submit() method directly.
- MDN
You can use the .requestSubmit() method instead, which does trigger the onsubmit event handler of the form and performs constraint validation on the form:
/* vanilla js replacement */
myForm = document.querySelector("form[name=myForm]")
myForm.querySelector("button").addEventListener('click', function() {
myForm.requestSubmit();
})
myForm.addEventListener('submit', function(e) {
e.preventDefault()
console.log("Submitting form");
})
<form name="myForm">
<input type="text" name="name" />
<button type="button">Click me</button>
</form>
The main downside to this method is that, unlike jQuery's .submit() method, requestSubmit() has weaker browser support.

How to combine two buttons into one?

I have following two buttons:
<button type="submit" id="gform_submit_button_1">Submit</button>
<button type="button" data-is_quote="1" data-button="simple_add_to_quote" data-product-type="simple" data-product-id="75448" id="add_to_quote">Submit</button>
the #gform_submit_button_1 button validates form entries before submitting data to the server
and the #add_to_quote button submits form data without validating it
I want to be able to validate the form & submit it using the #add_to_quote button. Any solution?
Trigger click event of gform_submit_button_1 button on click of add_to_quote.
$("#add_to_quote").click(function() {
$("#gform_submit_button_1").click();
});
I'm not sure that I get the problem right, but here is a possible solution :
Create a form element with an hidden input containing all the data-X values and a submit button that submits the form.
<form method="GET/POST" action="validation.php">
<input type="hidden" name="data-validation" data-is_quote="1" data-button="simple_add_to_quote" data-product-type="simple" data-product-id="75448" id="add_to_quote">
<input type="submit" value="submit" id="add_to_quote">
</form>
I hope it will help !
#Dhara Parmar solution is fine... but is missing the event.stopPropagation() and event.preventDefault() like this:
$("#add_to_quote").click(function() {
$(this).preventDefault(); //to stop submit
$(this).stopPropagation();//to avoid the event bubbling up to other submit buttons, if any...
$("#gform_submit_button_1").click();
});
you can call the validation and submit functions of the form directly from the type=button click handler to make it behave like a type=submit
$("#add_to_quote").click(function () {
if (!$("#TheForm").validate()) { //native validation triggered
return false;
} else {
$("#TheForm").submit()
}
});

keyup 13 event repeats implied submission - submit form on enter issue

UPDATE 10/9/15
My original question is below and is unclear and does not fully describe my problem because it focuses on the keyup event listener when its actually the double submission of the form (once from the change event and once from the implicit submission both triggered by keypress of the enter key) as the root problem... I have reviewed the code some more and here is an example demonstrating my true problem:
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
</head>
<body>
<form method="GET" action="#">
<input type="text" />
<input type="submit" />
</form>
<script>
$('form>input[type="text"]')
// Change event triggered by both enter key and tab key
.on('change', function (e) {
e.preventDefault();
console.log('change event');
$('form').submit(); //This emulates a more complex ajax request
});
$('form').submit(function (e) {
// You will notice the console logs this twice if you hit enter instead of tab.
console.log("form submitted");
});
</script>
</body>
</html>
If you enter something into the input box and hit the enter key then you will see in the console that the form submits twice, once from the change event and once from the implicit submission of the browser.
I want to stop the form submitting twice (you will notice I have already tried preventDefault in my code above). The answer appears to be to preventDefault specifically on the keypress (not keyup) of the enter key (many thanks to #JotaBe)
ORIGINAL QUESTION
So I have an event listener for the enter key on an input something like so
$(element)
.on('keyup', function (e) {
if (e.which === 13) {
event.trigger();
}
}); `
Specifically the code is from this plugin
This is interfering with the implied submission which is standard on most browsers, as per the W3 standard, and causing the form to submit twice.
What I would like to know, does the implicit submission happen before or after the explicit submission of my form with the event listener?
And for bonus points which version (or where can I find out which version) did 'implicit submission' get added to various browsers? (so I know how far back my code will be compatible)
Second question first
The implicit submission, although not with that name, exists at least from something as old as HTML 2 specs of novemeber 1995. Last lines of section 8.2:
When there is only one single-line text input field in a form, the user
agent should accept Enter in that field as a request to submit the form.
So, as we say in Spain, is as old as coughing.
And then, the main stuff
When you handle an event, unless you cancel the default action, when the code in your handler finishes running, the default action is executed.
Your code is triggering the event, and not cancelling the defautl action. That's why the submission happens twice, once for the handled event, and once for the additional triggered event.
In the case of jquery you've got to call event.preventDefault() to avoid the default action to execute.
Please look at this fiddle to check 2 things:
1) By default, when you press enter on a form, the form is submitted To be more precise, it must simulate a click on the first submit button of the form. Thus, if this button is disabled, or doesn't exist, nothing happens.
2) If you want to prevent the default behavior, you must handle the keypress (not keydown or keyup) event on the textbox, and invoke the event's preventDefault method.
3) According to the specs, this should only happen when there is a single textbox (of type text, number, date, url,email, etc.). But it doesn't work like this in most browsers, for example in desktop versions of Chrome 45, IE 10 and FF27 & FF33. I didn't test other versions.
Fiddle code:
// This suppres the default behavior of submitting the
// form when the enter key is pressed in the textbox
$('#form2').on('keypress', function (e) {
if (e.which === 13) {
e.preventDefault();
console.log('key press 13');
}
});
// This event is triggered when any form is submitted
// (in fact, the submission is prevented).
$('form').on('submit', function(e) {
console.log('Sending form', e.target.name);
e.preventDefault();
});
with this HTML:
<div>
<p>Form 1, default enter behavior, when there is only a textbox, and there is a submit button</p>
<p>If you press enter, it's submitted</p>
<form method="GET" id="form1">
<input type="text" />
<input type="submit" />
</form>
</div>
<div>
<p>Form 2: prevents default behavior on textbox</p>
<p>If you press enter the form is not submitted</p>
<form method="GET" id="form2">
<input type="text" />
<input type="submit" />
</form>
</div>
<div>
<p>Form 3: submit shuld only happen if there is only one textbox, but it depends on the browser</p>
<p>If you press enter the form should not be submitted, because there are several textboxes, but I bet it will be submitted</p>
<form method="GET" id="form3">
<input type="text" />
<input type="text" />
<input type="submit" />
</form>
</div>
add global variable like
var submited = true;
validate like
$(element)
.on('keyup', function (e) {
if (submited) {
submited = false ;
event.trigger();
}
});

Submit a form based on the javascript event

What I want is to be able to submit a form when ever a user presses some key like tab or enter (i.e. that will case him to lose focus) also clicking outside of the text field should trigger a submit. However when ever he click on the cancel button it should prevent the submit ion
html structure look like this
<form id="form">
<input id="text" onblur="$(this).closest('form').submit();">
<a id"submit">submit</a>
<a id"cancel">cancel</a>
</form>
Currently what happens is that when a user presses enter a form is submitted twice and it should be submitted only once. When he presses a cancel a form is submitted and cancelled right after that.
Does anyone have any idea how can I write some javascript code that can accomplish this behaviour (the idea for is take form the jira in-line edit mode and I am trying to construct something in similar manner)
I'm going to provide you with another you could approach this by using jQuery and it's .change() event handler. This way when the user clicks off of the input element, it'll trigger the .change() event and you can submit a form within it's callback function. If the user cancels then you can handle that event normally, same with the submit button click.
The Form:
<form id="form">
<input id="text">
<a id="cancel">cancel</a>
<a id="submit">submit</a>
</form>
The Javascript (jQuery):
$(document).ready(function(){
$('#submit').click(function(e){
e.preventDefault();
//submit the form
console.log('form submitted by button click')
});
$('#cancel').click(function(e) {
e.preventDefault();
//close form?
console.log('cancelled form');
});
$('#text').change(function(){
//submit the form
console.log('form submitted, maybe hide form now?');
});
});
The jsFiddle.
Keep submit flag to prevent duplication on form submit. Something like that
<form id="form">
<input id="text" onblur="submitForm('form');">
<button onclick="submitForm('form');">submit</button>
<button type="cancel">cancel</button>
</form>
<script>
var submitFlag = {};
function submitForm(id){
if(!submitFlag[id]){
submitFlag[id] = true;
$('#' + id).submit();
} else {
// do nothing
// alert('Form already submitted');
return;
}
}
</script>

Categories