Form validation executing incorrectly - javascript

My script disables the submit button for a form if the text-input is empty. I wrote a separate script that prompts a confirmation window before the user is allowed to submit updated content into the database. Both scripts work fine individually.
My problem arises when I try to combine both scripts using an if/else statement. The code below disables the button as expected and inserts the user-inputted data into the database once the submit button is enabled, however the confirmation window is entirely bypassed.
How can I get the confirmation window to appear again before anything is submitted?
JavaScript:
<script>
function validationCheck() {
if(document.getElementById('updateEventTitle').value==='') {
document.getElementById('updateBtn').disabled = true;
} else {
document.getElementById('updateBtn').disabled = false;
//Confirmation window
function updateEvent() {
var r =confirm('Do you want to update this item?');
if (r==true) {
window.location.href = 'server.php';
} else {
event.preventDefault();
}
}
}
}
</script>
HTML:
<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventTitle'>
<input type='text' id='updateEventTitle' name='myUpdateEventTitle' size='30' maxlength='40' placeholder='$row[eventName]' onkeyup='validationCheck()' required/>
<input class='btn btn-primary btn-sm' onclick='updateEvent()' type='submit' name='updateEventTitle' value='Update' id='updateBtn' disabled/>
</form>

You make reference to event in your two functions, but neither of them declared the event function argument. You need to set up the event argument in your functions:
function validationCheck(event)
function updateEvent(event)....
And, just nesting a function inside of another doesn't make the second one run. Instead, reorganize things a bit and don't set up your events with inline HTML event attributes, like onclick in the first place. Do your JavaScript work separate from your HTML.
Also, with a form, it's not the click event of the submit button that you should be handling, it's the submit event of the form.
Also (FYI), don't bother with self-terminating HTML tags.
Lastly, you've got your form action set to: editevent.php?updaterow=$iddata but later, if the user confirms that they want to submit, you are redirecting to: server.php. While that redirect will now work, the data that was inputted into the form will not be sent to it. Instead, with form validation, you simply test for situations where the submit should be halted and if that scenario doesn't exist, you simply do nothing and let the form submit as it was going to.
// Set up your event handlers in JavaScript, not with inline HTML
document.querySelector("form").addEventListener("submit", validationCheck);
document.getElementById("updateEventTitle").addEventListener("keyup", validationCheck);
// Get your DOM references just once, not every time the function runs
let eventTitle = document.getElementById('updateEventTitle');
let btnUpdate = document.getElementById('updateBtn');
function validationCheck(event) {
if(eventTitle.value==='') {
btnUpdate.disabled = true;
} else {
btnUpdate.disabled = false;
// If it was the submit button that was pressed...
if(event.type === "submit"){
// Confirmation window
// You only need to test for and handle situations where the form
// submit event should be halted. Otherwise, let the form submit to its action URL
if (!confirm('Do you want to update this item?') {
event.preventDefault();
}
}
}
}
<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventTitle'>
<input type='text' id='updateEventTitle' name='myUpdateEventTitle' size='30' maxlength='40' placeholder='$row[eventName]' required>
<input class='btn btn-primary btn-sm' type='submit' name='updateEventTitle' value='Update' id='updateBtn' disabled>
</form>

Is there a way to use #Scott Marcus method for multiple seperate forms on the same page, for example if I had a second additional form such as below? Javascript only seems to allow you to pass one param at a time using .getElementById
<form action='editevent.php?updaterow=$iddata' method='POST' id='updateEventDate'>
<input type='text' id='updateEventDate' name='myUpdateEventDate' size='15' maxlength='10' placeholder=$eventDate required/>
<input class='btn btn-primary btn-sm' type='submit' name='updateEventDate' value='Update' id='updateBtn' disabled>
</form>

Related

Javascript timeout problem with Flask backend [duplicate]

In the following page, with Firefox the remove button submits the form, but the add button does not.
How do I prevent the remove button from submitting the form?
function addItem() {
var v = $('form :hidden:last').attr('name');
var n = /(.*)input/.exec(v);
var newPrefix;
if (n[1].length == 0) {
newPrefix = '1';
} else {
newPrefix = parseInt(n[1]) + 1;
}
var oldElem = $('form tr:last');
var newElem = oldElem.clone(true);
var lastHidden = $('form :hidden:last');
lastHidden.val(newPrefix);
var pat = '=\"' + n[1] + 'input';
newElem.html(newElem.html().replace(new RegExp(pat, 'g'), '=\"' + newPrefix + 'input'));
newElem.appendTo('table');
$('form :hidden:last').val('');
}
function removeItem() {
var rows = $('form tr');
if (rows.length > 2) {
rows[rows.length - 1].html('');
$('form :hidden:last').val('');
} else {
alert('Cannot remove any more rows');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<html>
<body>
<form autocomplete="off" method="post" action="">
<p>Title:<input type="text" /></p>
<button onclick="addItem(); return false;">Add Item</button>
<button onclick="removeItem(); return false;">Remove Last Item</button>
<table>
<th>Name</th>
<tr>
<td><input type="text" id="input1" name="input1" /></td>
<td><input type="hidden" id="input2" name="input2" /></td>
</tr>
</table>
<input id="submit" type="submit" name="submit" value="Submit">
</form>
</body>
</html>
You're using an HTML5 button element. Remember the reason is this button has a default behavior of submit, as stated in the W3 specification as seen here:
W3C HTML5 Button
So you need to specify its type explicitly:
<button type="button">Button</button>
in order to override the default submit type. I just want to point out the reason why this happens.
Set the type on your buttons:
<button type="button" onclick="addItem(); return false;">Add Item</button>
<button type="button" onclick="removeItem(); return false;">Remove Last Item</button>
...that'll keep them from triggering a submit action when an exception occurs in the event handler. Then, fix your removeItem() function so that it doesn't trigger an exception:
function removeItem() {
var rows = $('form tr');
if ( rows.length > 2 ) {
// change: work on filtered jQuery object
rows.filter(":last").html('');
$('form :hidden:last').val('');
} else {
alert('Cannot remove any more rows');
}
}
Note the change: your original code extracted a HTML element from the jQuery set, and then tried to call a jQuery method on it - this threw an exception, resulting in the default behavior for the button.
FWIW, there's another way you could go with this... Wire up your event handlers using jQuery, and use the preventDefault() method on jQuery's event object to cancel the default behavior up-front:
$(function() // execute once the DOM has loaded
{
// wire up Add Item button click event
$("#AddItem").click(function(event)
{
event.preventDefault(); // cancel default behavior
//... rest of add logic
});
// wire up Remove Last Item button click event
$("RemoveLastItem").click(function(event)
{
event.preventDefault(); // cancel default behavior
//... rest of remove last logic
});
});
...
<button type="button" id="AddItem" name="AddItem">Add Item</button>
<button type="button" id="RemoveLastItem" name="RemoveLastItem">Remove Last Item</button>
This technique keeps all of your logic in one place, making it easier to debug... it also allows you to implement a fall-back by changing the type on the buttons back to submit and handling the event server-side - this is known as unobtrusive JavaScript.
Sometime ago I needed something very similar... and I got it.
So what I put here is how I do the tricks to have a form able to be submitted by JavaScript without any validating and execute validation only when the user presses a button (typically a send button).
For the example I will use a minimal form, only with two fields and a submit button.
Remember what is wanted:
From JavaScript it must be able to be submitted without any checking. However, if the user presses such a button, the validation must be done and form sent only if pass the validation.
Normally all would start from something near this (I removed all extra stuff not important):
<form method="post" id="theFormID" name="theFormID" action="">
<input type="text" id="Field1" name="Field1" />
<input type="text" id="Field2" name="Field2" />
<input type="submit" value="Send" onclick="JavaScript:return Validator();" />
</form>
See how form tag has no onsubmit="..." (remember it was a condition not to have it).
The problem is that the form is always submitted, no matter if onclick returns true or false.
If I change type="submit" for type="button", it seems to work but does not. It never sends the form, but that can be done easily.
So finally I used this:
<form method="post" id="theFormID" name="theFormID" action="">
<input type="text" id="Field1" name="Field1" />
<input type="text" id="Field2" name="Field2" />
<input type="button" value="Send" onclick="JavaScript:return Validator();" />
</form>
And on function Validator, where return True; is, I also add a JavaScript submit sentence, something similar to this:
function Validator(){
// ...bla bla bla... the checks
if( ){
document.getElementById('theFormID').submit();
return(true);
}else{
return(false);
}
}
The id="" is just for JavaScript getElementById, the name="" is just for it to appear on POST data.
On such way it works as I need.
I put this just for people that need no onsubmit function on the form, but make some validation when a button is press by user.
Why I need no onsubmit on form tag? Easy, on other JavaScript parts I need to perform a submit but I do not want there to be any validation.
The reason: If user is the one that performs the submit I want and need the validation to be done, but if it is JavaScript sometimes I need to perform the submit while such validations would avoid it.
It may sounds strange, but not when thinking for example: on a Login ... with some restrictions... like not allow to be used PHP sessions and neither cookies are allowed!
So any link must be converted to such form submit, so the login data is not lost.
When no login is yet done, it must also work. So no validation must be performed on links.
But I want to present a message to the user if the user has not entered both fields, user and pass. So if one is missing, the form must not be sent! there is the problem.
See the problem: the form must not be sent when one field is empty only if the user has pressed a button, if it is a JavaScript code it must be able to be sent.
If I do the work on onsubmit on the form tag, I would need to know if it is the user or other JavaScript. Since no parameters can be passed, it is not possible directly, so some people add a variable to tell if validation must be done or not. First thing on validation function is to check that variable value, etc... Too complicated and code does not say what is really wanted.
So the solution is not to have onsubmit on the form tag. Insead put it where it really is needed, on the button.
For the other side, why put onsubmit code since conceptually I do not want onsubmit validation. I really want button validation.
Not only the code is more clear, it is where it must be. Just remember this:
- I do not want JavaScript to validate the form (that must be always done by PHP on the server side)
- I want to show to the user a message telling all fields must not be empty, that needs JavaScript (client side)
So why some people (think or tell me) it must be done on an onsumbit validation? No, conceptually I am not doing a onsumbit validating at client side. I am just doing something on a button get pressed, so why not just let that to be implemented?
Well that code and style does the trick perfectly. On any JavaScript that I need to send the form I just put:
document.getElementById('theFormID').action='./GoToThisPage.php'; // Where to go
document.getElementById('theFormID').submit(); // Send POST data and go there
And that skips validation when I do not need it. It just sends the form and loads a different page, etc.
But if the user clicks the submit button (aka type="button" not type="submit") the validation is done before letting the form be submitted and if not valid not sent.
Well hope this helps others not to try long and complicated code. Just not use onsubmit if not needed, and use onclick. But just remember to change type="submit" to type="button" and please do not forget to do the submit() by JavaScript.
I agree with Shog9, though I might instead use:
<input type = "button" onClick="addItem(); return false;" value="Add Item" />
According to w3schools, the <button> tag has different behavior on different browsers.
You can simply get the reference of your buttons using jQuery, and prevent its propagation like below:
$(document).ready(function () {
$('#BUTTON_ID').click(function(e) {
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
return false;
});});
$("form").submit(function () { return false; });
that will prevent the button from submitting or you can just change the button type to "button" <input type="button"/> instead of <input type="submit"/>
Which will only work if this button isn't the only button in this form.
Suppose your HTML form has id="form_id"
<form id="form_id">
<!--your HTML code-->
</form>
Add this jQuery snippet to your code to see result,
$("#form_id").submit(function(){
return false;
});
Buttons like <button>Click to do something</button> are submit buttons.
You must add type
This is an html5 error like has been said, you can still have the button as a submit (if you want to cover both javascript and non javascript users) using it like:
<button type="submit" onclick="return false"> Register </button>
This way you will cancel the submit but still do whatever you are doing in jquery or javascript function`s and do the submit for users who dont have javascript.
Just add e.preventDefault(); in your method should prevent your page from submitting forms.
function myFunc(e){
e.preventDefault();
}
According to the MDN Web Docs
The preventDefault () method of the Event interface tells the user
agent that if the event is not explicitly processed, its default
action should not be taken into account as it would normally be. The
event continues to propagate as usual, unless one of its listeners
calls stopPropagation () or stopImmediatePropagation (), either of
which terminates the propagation.
The return false prevents the default behavior. but the return false breaks the bubbling of additional click events. This means if there are any other click bindings after this function gets called, those others do not Consider.
<button id="btnSubmit" type="button">PostData</button>
<Script> $("#btnSubmit").click(function(){
// do stuff
return false;
}); </Script>
Or simply you can put like this
<button type="submit" onclick="return false"> PostData</button>
I am sure that on FF the
removeItem
function encounter a JavaScript error, this not happend on IE
When javascript error appear the "return false" code won't run, making the page to postback
Set your button in normal way and use event.preventDefault like..
<button onclick="myFunc(e)"> Remove </button>
...
...
In function...
function myFunc(e){
e.preventDefault();
}
return false;
You can return false at the end of the function or after the function call.
Just as long as it's the last thing that happens, the form will not submit.
if you have <input />
use it
<input type="button"/>
if you have <button>btn</button>
use it
<button type="button">btn</button>
Here's a simple approach:
$('.mybutton').click(function(){
/* Perform some button action ... */
alert("I don't like it when you press my button!");
/* Then, the most important part ... */
return false;
});
I'm not able to test this right now, but I would think you could use jQuery's preventDefault method.
The following sample code show you how to prevent button click from submitting form.
You may try my sample code:
<form autocomplete="off" method="post" action="">
<p>Title:
<input type="text" />
</p>
<input type="button" onclick="addItem()" value="Add Item">
<input type="button" onclick="removeItem()" value="Remove Last Item">
<table>
<th>Name</th>
<tr>
<td>
<input type="text" id="input1" name="input1" />
</td>
<td>
<input type="hidden" id="input2" name="input2" />
</td>
</tr>
</table>
<input id="submit" type="submit" name="submit" value="Submit">
</form>
<script language="javascript">
function addItem() {
return false;
}
function removeItem() {
return false;
}
</script>
The function removeItem actually contains an error, which makes the form button do it's default behaviour (submitting the form). The javascript error console will usually give a pointer in this case.
Check out the function removeItem in the javascript part:
The line:
rows[rows.length-1].html('');
doesn't work. Try this instead:
rows.eq(rows.length-1).html('');
https://developer.mozilla.org/pt-BR/docs/Web/API/HTMLFormElement/submit_event
Do your logic on the form onsubmit event
submitter Read only
An HTMLElement object which identifies the button or other element which was invoked to trigger the form being submitted.
onsubmit="(evt) => console.log(evt)"
The event itself will bring along the caller and some usefull info.
Just use evt.preventDefault(); (default submit) evt.stopPropagation(); (submit bubbling) if the caller is a

State is of my react app is not changing after clicking the button [duplicate]

In the following page, with Firefox the remove button submits the form, but the add button does not.
How do I prevent the remove button from submitting the form?
function addItem() {
var v = $('form :hidden:last').attr('name');
var n = /(.*)input/.exec(v);
var newPrefix;
if (n[1].length == 0) {
newPrefix = '1';
} else {
newPrefix = parseInt(n[1]) + 1;
}
var oldElem = $('form tr:last');
var newElem = oldElem.clone(true);
var lastHidden = $('form :hidden:last');
lastHidden.val(newPrefix);
var pat = '=\"' + n[1] + 'input';
newElem.html(newElem.html().replace(new RegExp(pat, 'g'), '=\"' + newPrefix + 'input'));
newElem.appendTo('table');
$('form :hidden:last').val('');
}
function removeItem() {
var rows = $('form tr');
if (rows.length > 2) {
rows[rows.length - 1].html('');
$('form :hidden:last').val('');
} else {
alert('Cannot remove any more rows');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<html>
<body>
<form autocomplete="off" method="post" action="">
<p>Title:<input type="text" /></p>
<button onclick="addItem(); return false;">Add Item</button>
<button onclick="removeItem(); return false;">Remove Last Item</button>
<table>
<th>Name</th>
<tr>
<td><input type="text" id="input1" name="input1" /></td>
<td><input type="hidden" id="input2" name="input2" /></td>
</tr>
</table>
<input id="submit" type="submit" name="submit" value="Submit">
</form>
</body>
</html>
You're using an HTML5 button element. Remember the reason is this button has a default behavior of submit, as stated in the W3 specification as seen here:
W3C HTML5 Button
So you need to specify its type explicitly:
<button type="button">Button</button>
in order to override the default submit type. I just want to point out the reason why this happens.
Set the type on your buttons:
<button type="button" onclick="addItem(); return false;">Add Item</button>
<button type="button" onclick="removeItem(); return false;">Remove Last Item</button>
...that'll keep them from triggering a submit action when an exception occurs in the event handler. Then, fix your removeItem() function so that it doesn't trigger an exception:
function removeItem() {
var rows = $('form tr');
if ( rows.length > 2 ) {
// change: work on filtered jQuery object
rows.filter(":last").html('');
$('form :hidden:last').val('');
} else {
alert('Cannot remove any more rows');
}
}
Note the change: your original code extracted a HTML element from the jQuery set, and then tried to call a jQuery method on it - this threw an exception, resulting in the default behavior for the button.
FWIW, there's another way you could go with this... Wire up your event handlers using jQuery, and use the preventDefault() method on jQuery's event object to cancel the default behavior up-front:
$(function() // execute once the DOM has loaded
{
// wire up Add Item button click event
$("#AddItem").click(function(event)
{
event.preventDefault(); // cancel default behavior
//... rest of add logic
});
// wire up Remove Last Item button click event
$("RemoveLastItem").click(function(event)
{
event.preventDefault(); // cancel default behavior
//... rest of remove last logic
});
});
...
<button type="button" id="AddItem" name="AddItem">Add Item</button>
<button type="button" id="RemoveLastItem" name="RemoveLastItem">Remove Last Item</button>
This technique keeps all of your logic in one place, making it easier to debug... it also allows you to implement a fall-back by changing the type on the buttons back to submit and handling the event server-side - this is known as unobtrusive JavaScript.
Sometime ago I needed something very similar... and I got it.
So what I put here is how I do the tricks to have a form able to be submitted by JavaScript without any validating and execute validation only when the user presses a button (typically a send button).
For the example I will use a minimal form, only with two fields and a submit button.
Remember what is wanted:
From JavaScript it must be able to be submitted without any checking. However, if the user presses such a button, the validation must be done and form sent only if pass the validation.
Normally all would start from something near this (I removed all extra stuff not important):
<form method="post" id="theFormID" name="theFormID" action="">
<input type="text" id="Field1" name="Field1" />
<input type="text" id="Field2" name="Field2" />
<input type="submit" value="Send" onclick="JavaScript:return Validator();" />
</form>
See how form tag has no onsubmit="..." (remember it was a condition not to have it).
The problem is that the form is always submitted, no matter if onclick returns true or false.
If I change type="submit" for type="button", it seems to work but does not. It never sends the form, but that can be done easily.
So finally I used this:
<form method="post" id="theFormID" name="theFormID" action="">
<input type="text" id="Field1" name="Field1" />
<input type="text" id="Field2" name="Field2" />
<input type="button" value="Send" onclick="JavaScript:return Validator();" />
</form>
And on function Validator, where return True; is, I also add a JavaScript submit sentence, something similar to this:
function Validator(){
// ...bla bla bla... the checks
if( ){
document.getElementById('theFormID').submit();
return(true);
}else{
return(false);
}
}
The id="" is just for JavaScript getElementById, the name="" is just for it to appear on POST data.
On such way it works as I need.
I put this just for people that need no onsubmit function on the form, but make some validation when a button is press by user.
Why I need no onsubmit on form tag? Easy, on other JavaScript parts I need to perform a submit but I do not want there to be any validation.
The reason: If user is the one that performs the submit I want and need the validation to be done, but if it is JavaScript sometimes I need to perform the submit while such validations would avoid it.
It may sounds strange, but not when thinking for example: on a Login ... with some restrictions... like not allow to be used PHP sessions and neither cookies are allowed!
So any link must be converted to such form submit, so the login data is not lost.
When no login is yet done, it must also work. So no validation must be performed on links.
But I want to present a message to the user if the user has not entered both fields, user and pass. So if one is missing, the form must not be sent! there is the problem.
See the problem: the form must not be sent when one field is empty only if the user has pressed a button, if it is a JavaScript code it must be able to be sent.
If I do the work on onsubmit on the form tag, I would need to know if it is the user or other JavaScript. Since no parameters can be passed, it is not possible directly, so some people add a variable to tell if validation must be done or not. First thing on validation function is to check that variable value, etc... Too complicated and code does not say what is really wanted.
So the solution is not to have onsubmit on the form tag. Insead put it where it really is needed, on the button.
For the other side, why put onsubmit code since conceptually I do not want onsubmit validation. I really want button validation.
Not only the code is more clear, it is where it must be. Just remember this:
- I do not want JavaScript to validate the form (that must be always done by PHP on the server side)
- I want to show to the user a message telling all fields must not be empty, that needs JavaScript (client side)
So why some people (think or tell me) it must be done on an onsumbit validation? No, conceptually I am not doing a onsumbit validating at client side. I am just doing something on a button get pressed, so why not just let that to be implemented?
Well that code and style does the trick perfectly. On any JavaScript that I need to send the form I just put:
document.getElementById('theFormID').action='./GoToThisPage.php'; // Where to go
document.getElementById('theFormID').submit(); // Send POST data and go there
And that skips validation when I do not need it. It just sends the form and loads a different page, etc.
But if the user clicks the submit button (aka type="button" not type="submit") the validation is done before letting the form be submitted and if not valid not sent.
Well hope this helps others not to try long and complicated code. Just not use onsubmit if not needed, and use onclick. But just remember to change type="submit" to type="button" and please do not forget to do the submit() by JavaScript.
I agree with Shog9, though I might instead use:
<input type = "button" onClick="addItem(); return false;" value="Add Item" />
According to w3schools, the <button> tag has different behavior on different browsers.
You can simply get the reference of your buttons using jQuery, and prevent its propagation like below:
$(document).ready(function () {
$('#BUTTON_ID').click(function(e) {
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
return false;
});});
$("form").submit(function () { return false; });
that will prevent the button from submitting or you can just change the button type to "button" <input type="button"/> instead of <input type="submit"/>
Which will only work if this button isn't the only button in this form.
Suppose your HTML form has id="form_id"
<form id="form_id">
<!--your HTML code-->
</form>
Add this jQuery snippet to your code to see result,
$("#form_id").submit(function(){
return false;
});
Buttons like <button>Click to do something</button> are submit buttons.
You must add type
This is an html5 error like has been said, you can still have the button as a submit (if you want to cover both javascript and non javascript users) using it like:
<button type="submit" onclick="return false"> Register </button>
This way you will cancel the submit but still do whatever you are doing in jquery or javascript function`s and do the submit for users who dont have javascript.
Just add e.preventDefault(); in your method should prevent your page from submitting forms.
function myFunc(e){
e.preventDefault();
}
According to the MDN Web Docs
The preventDefault () method of the Event interface tells the user
agent that if the event is not explicitly processed, its default
action should not be taken into account as it would normally be. The
event continues to propagate as usual, unless one of its listeners
calls stopPropagation () or stopImmediatePropagation (), either of
which terminates the propagation.
The return false prevents the default behavior. but the return false breaks the bubbling of additional click events. This means if there are any other click bindings after this function gets called, those others do not Consider.
<button id="btnSubmit" type="button">PostData</button>
<Script> $("#btnSubmit").click(function(){
// do stuff
return false;
}); </Script>
Or simply you can put like this
<button type="submit" onclick="return false"> PostData</button>
I am sure that on FF the
removeItem
function encounter a JavaScript error, this not happend on IE
When javascript error appear the "return false" code won't run, making the page to postback
Set your button in normal way and use event.preventDefault like..
<button onclick="myFunc(e)"> Remove </button>
...
...
In function...
function myFunc(e){
e.preventDefault();
}
return false;
You can return false at the end of the function or after the function call.
Just as long as it's the last thing that happens, the form will not submit.
if you have <input />
use it
<input type="button"/>
if you have <button>btn</button>
use it
<button type="button">btn</button>
Here's a simple approach:
$('.mybutton').click(function(){
/* Perform some button action ... */
alert("I don't like it when you press my button!");
/* Then, the most important part ... */
return false;
});
I'm not able to test this right now, but I would think you could use jQuery's preventDefault method.
The following sample code show you how to prevent button click from submitting form.
You may try my sample code:
<form autocomplete="off" method="post" action="">
<p>Title:
<input type="text" />
</p>
<input type="button" onclick="addItem()" value="Add Item">
<input type="button" onclick="removeItem()" value="Remove Last Item">
<table>
<th>Name</th>
<tr>
<td>
<input type="text" id="input1" name="input1" />
</td>
<td>
<input type="hidden" id="input2" name="input2" />
</td>
</tr>
</table>
<input id="submit" type="submit" name="submit" value="Submit">
</form>
<script language="javascript">
function addItem() {
return false;
}
function removeItem() {
return false;
}
</script>
The function removeItem actually contains an error, which makes the form button do it's default behaviour (submitting the form). The javascript error console will usually give a pointer in this case.
Check out the function removeItem in the javascript part:
The line:
rows[rows.length-1].html('');
doesn't work. Try this instead:
rows.eq(rows.length-1).html('');
https://developer.mozilla.org/pt-BR/docs/Web/API/HTMLFormElement/submit_event
Do your logic on the form onsubmit event
submitter Read only
An HTMLElement object which identifies the button or other element which was invoked to trigger the form being submitted.
onsubmit="(evt) => console.log(evt)"
The event itself will bring along the caller and some usefull info.
Just use evt.preventDefault(); (default submit) evt.stopPropagation(); (submit bubbling) if the caller is a

Calculations with JavaScript without submitting the form [duplicate]

In the following page, with Firefox the remove button submits the form, but the add button does not.
How do I prevent the remove button from submitting the form?
function addItem() {
var v = $('form :hidden:last').attr('name');
var n = /(.*)input/.exec(v);
var newPrefix;
if (n[1].length == 0) {
newPrefix = '1';
} else {
newPrefix = parseInt(n[1]) + 1;
}
var oldElem = $('form tr:last');
var newElem = oldElem.clone(true);
var lastHidden = $('form :hidden:last');
lastHidden.val(newPrefix);
var pat = '=\"' + n[1] + 'input';
newElem.html(newElem.html().replace(new RegExp(pat, 'g'), '=\"' + newPrefix + 'input'));
newElem.appendTo('table');
$('form :hidden:last').val('');
}
function removeItem() {
var rows = $('form tr');
if (rows.length > 2) {
rows[rows.length - 1].html('');
$('form :hidden:last').val('');
} else {
alert('Cannot remove any more rows');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<html>
<body>
<form autocomplete="off" method="post" action="">
<p>Title:<input type="text" /></p>
<button onclick="addItem(); return false;">Add Item</button>
<button onclick="removeItem(); return false;">Remove Last Item</button>
<table>
<th>Name</th>
<tr>
<td><input type="text" id="input1" name="input1" /></td>
<td><input type="hidden" id="input2" name="input2" /></td>
</tr>
</table>
<input id="submit" type="submit" name="submit" value="Submit">
</form>
</body>
</html>
You're using an HTML5 button element. Remember the reason is this button has a default behavior of submit, as stated in the W3 specification as seen here:
W3C HTML5 Button
So you need to specify its type explicitly:
<button type="button">Button</button>
in order to override the default submit type. I just want to point out the reason why this happens.
Set the type on your buttons:
<button type="button" onclick="addItem(); return false;">Add Item</button>
<button type="button" onclick="removeItem(); return false;">Remove Last Item</button>
...that'll keep them from triggering a submit action when an exception occurs in the event handler. Then, fix your removeItem() function so that it doesn't trigger an exception:
function removeItem() {
var rows = $('form tr');
if ( rows.length > 2 ) {
// change: work on filtered jQuery object
rows.filter(":last").html('');
$('form :hidden:last').val('');
} else {
alert('Cannot remove any more rows');
}
}
Note the change: your original code extracted a HTML element from the jQuery set, and then tried to call a jQuery method on it - this threw an exception, resulting in the default behavior for the button.
FWIW, there's another way you could go with this... Wire up your event handlers using jQuery, and use the preventDefault() method on jQuery's event object to cancel the default behavior up-front:
$(function() // execute once the DOM has loaded
{
// wire up Add Item button click event
$("#AddItem").click(function(event)
{
event.preventDefault(); // cancel default behavior
//... rest of add logic
});
// wire up Remove Last Item button click event
$("RemoveLastItem").click(function(event)
{
event.preventDefault(); // cancel default behavior
//... rest of remove last logic
});
});
...
<button type="button" id="AddItem" name="AddItem">Add Item</button>
<button type="button" id="RemoveLastItem" name="RemoveLastItem">Remove Last Item</button>
This technique keeps all of your logic in one place, making it easier to debug... it also allows you to implement a fall-back by changing the type on the buttons back to submit and handling the event server-side - this is known as unobtrusive JavaScript.
Sometime ago I needed something very similar... and I got it.
So what I put here is how I do the tricks to have a form able to be submitted by JavaScript without any validating and execute validation only when the user presses a button (typically a send button).
For the example I will use a minimal form, only with two fields and a submit button.
Remember what is wanted:
From JavaScript it must be able to be submitted without any checking. However, if the user presses such a button, the validation must be done and form sent only if pass the validation.
Normally all would start from something near this (I removed all extra stuff not important):
<form method="post" id="theFormID" name="theFormID" action="">
<input type="text" id="Field1" name="Field1" />
<input type="text" id="Field2" name="Field2" />
<input type="submit" value="Send" onclick="JavaScript:return Validator();" />
</form>
See how form tag has no onsubmit="..." (remember it was a condition not to have it).
The problem is that the form is always submitted, no matter if onclick returns true or false.
If I change type="submit" for type="button", it seems to work but does not. It never sends the form, but that can be done easily.
So finally I used this:
<form method="post" id="theFormID" name="theFormID" action="">
<input type="text" id="Field1" name="Field1" />
<input type="text" id="Field2" name="Field2" />
<input type="button" value="Send" onclick="JavaScript:return Validator();" />
</form>
And on function Validator, where return True; is, I also add a JavaScript submit sentence, something similar to this:
function Validator(){
// ...bla bla bla... the checks
if( ){
document.getElementById('theFormID').submit();
return(true);
}else{
return(false);
}
}
The id="" is just for JavaScript getElementById, the name="" is just for it to appear on POST data.
On such way it works as I need.
I put this just for people that need no onsubmit function on the form, but make some validation when a button is press by user.
Why I need no onsubmit on form tag? Easy, on other JavaScript parts I need to perform a submit but I do not want there to be any validation.
The reason: If user is the one that performs the submit I want and need the validation to be done, but if it is JavaScript sometimes I need to perform the submit while such validations would avoid it.
It may sounds strange, but not when thinking for example: on a Login ... with some restrictions... like not allow to be used PHP sessions and neither cookies are allowed!
So any link must be converted to such form submit, so the login data is not lost.
When no login is yet done, it must also work. So no validation must be performed on links.
But I want to present a message to the user if the user has not entered both fields, user and pass. So if one is missing, the form must not be sent! there is the problem.
See the problem: the form must not be sent when one field is empty only if the user has pressed a button, if it is a JavaScript code it must be able to be sent.
If I do the work on onsubmit on the form tag, I would need to know if it is the user or other JavaScript. Since no parameters can be passed, it is not possible directly, so some people add a variable to tell if validation must be done or not. First thing on validation function is to check that variable value, etc... Too complicated and code does not say what is really wanted.
So the solution is not to have onsubmit on the form tag. Insead put it where it really is needed, on the button.
For the other side, why put onsubmit code since conceptually I do not want onsubmit validation. I really want button validation.
Not only the code is more clear, it is where it must be. Just remember this:
- I do not want JavaScript to validate the form (that must be always done by PHP on the server side)
- I want to show to the user a message telling all fields must not be empty, that needs JavaScript (client side)
So why some people (think or tell me) it must be done on an onsumbit validation? No, conceptually I am not doing a onsumbit validating at client side. I am just doing something on a button get pressed, so why not just let that to be implemented?
Well that code and style does the trick perfectly. On any JavaScript that I need to send the form I just put:
document.getElementById('theFormID').action='./GoToThisPage.php'; // Where to go
document.getElementById('theFormID').submit(); // Send POST data and go there
And that skips validation when I do not need it. It just sends the form and loads a different page, etc.
But if the user clicks the submit button (aka type="button" not type="submit") the validation is done before letting the form be submitted and if not valid not sent.
Well hope this helps others not to try long and complicated code. Just not use onsubmit if not needed, and use onclick. But just remember to change type="submit" to type="button" and please do not forget to do the submit() by JavaScript.
I agree with Shog9, though I might instead use:
<input type = "button" onClick="addItem(); return false;" value="Add Item" />
According to w3schools, the <button> tag has different behavior on different browsers.
You can simply get the reference of your buttons using jQuery, and prevent its propagation like below:
$(document).ready(function () {
$('#BUTTON_ID').click(function(e) {
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
return false;
});});
$("form").submit(function () { return false; });
that will prevent the button from submitting or you can just change the button type to "button" <input type="button"/> instead of <input type="submit"/>
Which will only work if this button isn't the only button in this form.
Suppose your HTML form has id="form_id"
<form id="form_id">
<!--your HTML code-->
</form>
Add this jQuery snippet to your code to see result,
$("#form_id").submit(function(){
return false;
});
Buttons like <button>Click to do something</button> are submit buttons.
You must add type
This is an html5 error like has been said, you can still have the button as a submit (if you want to cover both javascript and non javascript users) using it like:
<button type="submit" onclick="return false"> Register </button>
This way you will cancel the submit but still do whatever you are doing in jquery or javascript function`s and do the submit for users who dont have javascript.
Just add e.preventDefault(); in your method should prevent your page from submitting forms.
function myFunc(e){
e.preventDefault();
}
According to the MDN Web Docs
The preventDefault () method of the Event interface tells the user
agent that if the event is not explicitly processed, its default
action should not be taken into account as it would normally be. The
event continues to propagate as usual, unless one of its listeners
calls stopPropagation () or stopImmediatePropagation (), either of
which terminates the propagation.
The return false prevents the default behavior. but the return false breaks the bubbling of additional click events. This means if there are any other click bindings after this function gets called, those others do not Consider.
<button id="btnSubmit" type="button">PostData</button>
<Script> $("#btnSubmit").click(function(){
// do stuff
return false;
}); </Script>
Or simply you can put like this
<button type="submit" onclick="return false"> PostData</button>
I am sure that on FF the
removeItem
function encounter a JavaScript error, this not happend on IE
When javascript error appear the "return false" code won't run, making the page to postback
Set your button in normal way and use event.preventDefault like..
<button onclick="myFunc(e)"> Remove </button>
...
...
In function...
function myFunc(e){
e.preventDefault();
}
return false;
You can return false at the end of the function or after the function call.
Just as long as it's the last thing that happens, the form will not submit.
if you have <input />
use it
<input type="button"/>
if you have <button>btn</button>
use it
<button type="button">btn</button>
Here's a simple approach:
$('.mybutton').click(function(){
/* Perform some button action ... */
alert("I don't like it when you press my button!");
/* Then, the most important part ... */
return false;
});
I'm not able to test this right now, but I would think you could use jQuery's preventDefault method.
The following sample code show you how to prevent button click from submitting form.
You may try my sample code:
<form autocomplete="off" method="post" action="">
<p>Title:
<input type="text" />
</p>
<input type="button" onclick="addItem()" value="Add Item">
<input type="button" onclick="removeItem()" value="Remove Last Item">
<table>
<th>Name</th>
<tr>
<td>
<input type="text" id="input1" name="input1" />
</td>
<td>
<input type="hidden" id="input2" name="input2" />
</td>
</tr>
</table>
<input id="submit" type="submit" name="submit" value="Submit">
</form>
<script language="javascript">
function addItem() {
return false;
}
function removeItem() {
return false;
}
</script>
The function removeItem actually contains an error, which makes the form button do it's default behaviour (submitting the form). The javascript error console will usually give a pointer in this case.
Check out the function removeItem in the javascript part:
The line:
rows[rows.length-1].html('');
doesn't work. Try this instead:
rows.eq(rows.length-1).html('');
https://developer.mozilla.org/pt-BR/docs/Web/API/HTMLFormElement/submit_event
Do your logic on the form onsubmit event
submitter Read only
An HTMLElement object which identifies the button or other element which was invoked to trigger the form being submitted.
onsubmit="(evt) => console.log(evt)"
The event itself will bring along the caller and some usefull info.
Just use evt.preventDefault(); (default submit) evt.stopPropagation(); (submit bubbling) if the caller is a

What is the proper way to submit a form with JS and still post all form data successfully?

I'm working with an embedded app on our dev site and when I click the submit button inside the iframe, I am triggering a manual submission event on another form (not in an iframe) on that page. If I manually click the submit button for the form, my data posts and everything works correctly. However, I want to eliminate an extra user click and submit the external form automatically when a user submits the other form inside the iframe.
I've got everything working correctly on a base level. When a user clicks the submit button in the iframe, I am using JQuery to grab values from inside the iframe and set values in this external form. Using the jquery 'submit()' event, I am then able to submit that external form. The problem is, the page refreshes and the data doesn't go anywhere. If I remove the 'submit()' event and manually click the submit button, the form posts and in this case, adds a product with custom data to the product cart.
As a proof of concept, this is my 'iframed' HTML.
<!DOCTYPE html>
<html>
<head></head>
<body>
<h1>Proof of Concept</h1>
<p>Total cost: $<span id="cust_price">222.22</span> plus shipping.</p>
<p>Quote number: <span id="quot_num">1546751962211</p>
<form method="POST" enctype="multipart/form-data" id="newQuoteForm">
<button type="submit" class="btn btn-primary" name="new-app-btn">Add to Cart</button>
</form>
</body>
<footer>
</footer>
</html>
Here is my on-page form that is OUTSIDE the iFrame.
<form method="POST" enctype="multipart/form-data" id="outer-quote-form" action="/checkout/">
<label class="quote_number">Quote Number:
<input type="text" id="quote_number" name="quote_number" value="">
</label>
<label class="custom_price">price:
<input type="text" id="custom_price" name="custom_price" value="">
</label>
<button type="submit" class="btn btn-primary" name="ws-add-to-cart">Add to Cart</button>
</form>
Then, I have JQuery working to grab the iframed values and puts them in the exterior form. Afterwards, it fires a 'submit()' event on that form.
<script>
jQuery('#newQuoteApp').load(function() {
var iFrameDOM = jQuery("iframe#newQuoteApp").contents();
jQuery('#newQuoteApp').contents().find('#newQuoteForm').submit(function() {
jQuery("input#custom_price").val(jQuery('#newQuoteApp').contents().find('#cust_price').text()); // updated
jQuery("input#quote_number").val(jQuery('#newQuoteApp').contents().find('#quot_num').text());
jQuery("#outer-quote-form").submit();
return true; //return false prevents submit
});
});
</script>
Except when the jquery submit() event fires, the form appears to submit and the page refreshes but no data is posting as it does when I manually submit the form. Is there an extra step here or a better way to fire the form submit with post data?
Edit: Adding the PHP function that isn't firing on jquery submit() for context.
if (isset($_POST['ws-add-to-cart'])) {
add_action( 'init', 'add_product_to_cart' );
function add_product_to_cart() {
global $woocommerce;
global $product;
$product_id = 138;
$woocommerce->cart->add_to_cart($product_id);
}
header("Location:https://www.devsite.com/checkout/");
}
The reason for the form not submitting because you are submitting the whole form without the submit button which is <button type="submit" class="btn btn-primary" name="ws-add-to-cart">Add to Cart</button> which you have declared in php to get a post request like this
if (isset($_POST['ws-add-to-cart'])) {...
When you call submit(); on the form via the get method, you see '/new-quote/?quote_number=1546751962211&custom_price=222.22'
but where's ws-add-to-cart, it's not submitting and that's the reason why php isn't getting your request
The fix will be to add .click() on the submit button instead of submitting the form
<script>
function enterVals($val){
var price = $val.price;
document.getElementById("quote_number").value = $val.num
document.getElementById("custom_price").value = $val.price
document.getElementsByName("ws-add-to-cart").click();
}
</script>
Or in your script in case you want to use jquery, this is the fix
<script>
jQuery('#newQuoteApp').load(function() {
var iFrameDOM = jQuery("iframe#newQuoteApp").contents();
jQuery('#newQuoteApp').contents().find('#newQuoteForm').submit(function() {
jQuery("input#custom_price").val(jQuery('#newQuoteApp').contents().find('#cust_price').text()); // updated
jQuery("input#quote_number").val(jQuery('#newQuoteApp').contents().find('#quot_num').text());
jQuery("button[name=ws-add-to-cart]").click();
return true; //return false prevents submit
});
});
</script>
This is definitely the answer and sorry for my stupidity, i didn't pay required attention before
try removing return true from your js code
if that doesn't work, try changing the <form method="POST" to <form method="GET" to debug the values in the url just for checking that the form actually fires up with values
Alternative method: Old school method
code for page OUTSIDE the Iframe
<script>
function enterVals($val){
var price = $val.price;
document.getElementById("quote_number").value = $val.num
document.getElementById("custom_price").value = $val.price
document.getElementById("outer-quote-form").submit();
}
</script>
code for the Iframe file
<script type="text/javascript">
$('#newQuoteForm').on('submit', function(event) {
var Page = window.parent;
var allVals = {
price:$('#cust_price').text(),
num:$('#quot_num').text()
}
Page.enterVals(allVals);
event.preventDefault();
});
</script>
Explanation
window.parent refers to the parent window where the iframe is loaded on, with reference to this we can trigger functions that are in the parent window so by this, we created a variable and added the information which is sent by the function enterVals() to the window
The enterVals() function just puts the values and submits the form without any jQuery.
What is the proper way to submit a form with JS?
This might not be the 'best' way to submit a form with js but is cross-browser which is good

Button inside form automatically acting as submit [duplicate]

In the following page, with Firefox the remove button submits the form, but the add button does not.
How do I prevent the remove button from submitting the form?
function addItem() {
var v = $('form :hidden:last').attr('name');
var n = /(.*)input/.exec(v);
var newPrefix;
if (n[1].length == 0) {
newPrefix = '1';
} else {
newPrefix = parseInt(n[1]) + 1;
}
var oldElem = $('form tr:last');
var newElem = oldElem.clone(true);
var lastHidden = $('form :hidden:last');
lastHidden.val(newPrefix);
var pat = '=\"' + n[1] + 'input';
newElem.html(newElem.html().replace(new RegExp(pat, 'g'), '=\"' + newPrefix + 'input'));
newElem.appendTo('table');
$('form :hidden:last').val('');
}
function removeItem() {
var rows = $('form tr');
if (rows.length > 2) {
rows[rows.length - 1].html('');
$('form :hidden:last').val('');
} else {
alert('Cannot remove any more rows');
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<html>
<body>
<form autocomplete="off" method="post" action="">
<p>Title:<input type="text" /></p>
<button onclick="addItem(); return false;">Add Item</button>
<button onclick="removeItem(); return false;">Remove Last Item</button>
<table>
<th>Name</th>
<tr>
<td><input type="text" id="input1" name="input1" /></td>
<td><input type="hidden" id="input2" name="input2" /></td>
</tr>
</table>
<input id="submit" type="submit" name="submit" value="Submit">
</form>
</body>
</html>
You're using an HTML5 button element. Remember the reason is this button has a default behavior of submit, as stated in the W3 specification as seen here:
W3C HTML5 Button
So you need to specify its type explicitly:
<button type="button">Button</button>
in order to override the default submit type. I just want to point out the reason why this happens.
Set the type on your buttons:
<button type="button" onclick="addItem(); return false;">Add Item</button>
<button type="button" onclick="removeItem(); return false;">Remove Last Item</button>
...that'll keep them from triggering a submit action when an exception occurs in the event handler. Then, fix your removeItem() function so that it doesn't trigger an exception:
function removeItem() {
var rows = $('form tr');
if ( rows.length > 2 ) {
// change: work on filtered jQuery object
rows.filter(":last").html('');
$('form :hidden:last').val('');
} else {
alert('Cannot remove any more rows');
}
}
Note the change: your original code extracted a HTML element from the jQuery set, and then tried to call a jQuery method on it - this threw an exception, resulting in the default behavior for the button.
FWIW, there's another way you could go with this... Wire up your event handlers using jQuery, and use the preventDefault() method on jQuery's event object to cancel the default behavior up-front:
$(function() // execute once the DOM has loaded
{
// wire up Add Item button click event
$("#AddItem").click(function(event)
{
event.preventDefault(); // cancel default behavior
//... rest of add logic
});
// wire up Remove Last Item button click event
$("RemoveLastItem").click(function(event)
{
event.preventDefault(); // cancel default behavior
//... rest of remove last logic
});
});
...
<button type="button" id="AddItem" name="AddItem">Add Item</button>
<button type="button" id="RemoveLastItem" name="RemoveLastItem">Remove Last Item</button>
This technique keeps all of your logic in one place, making it easier to debug... it also allows you to implement a fall-back by changing the type on the buttons back to submit and handling the event server-side - this is known as unobtrusive JavaScript.
Sometime ago I needed something very similar... and I got it.
So what I put here is how I do the tricks to have a form able to be submitted by JavaScript without any validating and execute validation only when the user presses a button (typically a send button).
For the example I will use a minimal form, only with two fields and a submit button.
Remember what is wanted:
From JavaScript it must be able to be submitted without any checking. However, if the user presses such a button, the validation must be done and form sent only if pass the validation.
Normally all would start from something near this (I removed all extra stuff not important):
<form method="post" id="theFormID" name="theFormID" action="">
<input type="text" id="Field1" name="Field1" />
<input type="text" id="Field2" name="Field2" />
<input type="submit" value="Send" onclick="JavaScript:return Validator();" />
</form>
See how form tag has no onsubmit="..." (remember it was a condition not to have it).
The problem is that the form is always submitted, no matter if onclick returns true or false.
If I change type="submit" for type="button", it seems to work but does not. It never sends the form, but that can be done easily.
So finally I used this:
<form method="post" id="theFormID" name="theFormID" action="">
<input type="text" id="Field1" name="Field1" />
<input type="text" id="Field2" name="Field2" />
<input type="button" value="Send" onclick="JavaScript:return Validator();" />
</form>
And on function Validator, where return True; is, I also add a JavaScript submit sentence, something similar to this:
function Validator(){
// ...bla bla bla... the checks
if( ){
document.getElementById('theFormID').submit();
return(true);
}else{
return(false);
}
}
The id="" is just for JavaScript getElementById, the name="" is just for it to appear on POST data.
On such way it works as I need.
I put this just for people that need no onsubmit function on the form, but make some validation when a button is press by user.
Why I need no onsubmit on form tag? Easy, on other JavaScript parts I need to perform a submit but I do not want there to be any validation.
The reason: If user is the one that performs the submit I want and need the validation to be done, but if it is JavaScript sometimes I need to perform the submit while such validations would avoid it.
It may sounds strange, but not when thinking for example: on a Login ... with some restrictions... like not allow to be used PHP sessions and neither cookies are allowed!
So any link must be converted to such form submit, so the login data is not lost.
When no login is yet done, it must also work. So no validation must be performed on links.
But I want to present a message to the user if the user has not entered both fields, user and pass. So if one is missing, the form must not be sent! there is the problem.
See the problem: the form must not be sent when one field is empty only if the user has pressed a button, if it is a JavaScript code it must be able to be sent.
If I do the work on onsubmit on the form tag, I would need to know if it is the user or other JavaScript. Since no parameters can be passed, it is not possible directly, so some people add a variable to tell if validation must be done or not. First thing on validation function is to check that variable value, etc... Too complicated and code does not say what is really wanted.
So the solution is not to have onsubmit on the form tag. Insead put it where it really is needed, on the button.
For the other side, why put onsubmit code since conceptually I do not want onsubmit validation. I really want button validation.
Not only the code is more clear, it is where it must be. Just remember this:
- I do not want JavaScript to validate the form (that must be always done by PHP on the server side)
- I want to show to the user a message telling all fields must not be empty, that needs JavaScript (client side)
So why some people (think or tell me) it must be done on an onsumbit validation? No, conceptually I am not doing a onsumbit validating at client side. I am just doing something on a button get pressed, so why not just let that to be implemented?
Well that code and style does the trick perfectly. On any JavaScript that I need to send the form I just put:
document.getElementById('theFormID').action='./GoToThisPage.php'; // Where to go
document.getElementById('theFormID').submit(); // Send POST data and go there
And that skips validation when I do not need it. It just sends the form and loads a different page, etc.
But if the user clicks the submit button (aka type="button" not type="submit") the validation is done before letting the form be submitted and if not valid not sent.
Well hope this helps others not to try long and complicated code. Just not use onsubmit if not needed, and use onclick. But just remember to change type="submit" to type="button" and please do not forget to do the submit() by JavaScript.
I agree with Shog9, though I might instead use:
<input type = "button" onClick="addItem(); return false;" value="Add Item" />
According to w3schools, the <button> tag has different behavior on different browsers.
You can simply get the reference of your buttons using jQuery, and prevent its propagation like below:
$(document).ready(function () {
$('#BUTTON_ID').click(function(e) {
e.preventDefault();
e.stopPropagation();
e.stopImmediatePropagation();
return false;
});});
$("form").submit(function () { return false; });
that will prevent the button from submitting or you can just change the button type to "button" <input type="button"/> instead of <input type="submit"/>
Which will only work if this button isn't the only button in this form.
Suppose your HTML form has id="form_id"
<form id="form_id">
<!--your HTML code-->
</form>
Add this jQuery snippet to your code to see result,
$("#form_id").submit(function(){
return false;
});
Buttons like <button>Click to do something</button> are submit buttons.
You must add type
This is an html5 error like has been said, you can still have the button as a submit (if you want to cover both javascript and non javascript users) using it like:
<button type="submit" onclick="return false"> Register </button>
This way you will cancel the submit but still do whatever you are doing in jquery or javascript function`s and do the submit for users who dont have javascript.
Just add e.preventDefault(); in your method should prevent your page from submitting forms.
function myFunc(e){
e.preventDefault();
}
According to the MDN Web Docs
The preventDefault () method of the Event interface tells the user
agent that if the event is not explicitly processed, its default
action should not be taken into account as it would normally be. The
event continues to propagate as usual, unless one of its listeners
calls stopPropagation () or stopImmediatePropagation (), either of
which terminates the propagation.
The return false prevents the default behavior. but the return false breaks the bubbling of additional click events. This means if there are any other click bindings after this function gets called, those others do not Consider.
<button id="btnSubmit" type="button">PostData</button>
<Script> $("#btnSubmit").click(function(){
// do stuff
return false;
}); </Script>
Or simply you can put like this
<button type="submit" onclick="return false"> PostData</button>
I am sure that on FF the
removeItem
function encounter a JavaScript error, this not happend on IE
When javascript error appear the "return false" code won't run, making the page to postback
Set your button in normal way and use event.preventDefault like..
<button onclick="myFunc(e)"> Remove </button>
...
...
In function...
function myFunc(e){
e.preventDefault();
}
return false;
You can return false at the end of the function or after the function call.
Just as long as it's the last thing that happens, the form will not submit.
if you have <input />
use it
<input type="button"/>
if you have <button>btn</button>
use it
<button type="button">btn</button>
Here's a simple approach:
$('.mybutton').click(function(){
/* Perform some button action ... */
alert("I don't like it when you press my button!");
/* Then, the most important part ... */
return false;
});
I'm not able to test this right now, but I would think you could use jQuery's preventDefault method.
The following sample code show you how to prevent button click from submitting form.
You may try my sample code:
<form autocomplete="off" method="post" action="">
<p>Title:
<input type="text" />
</p>
<input type="button" onclick="addItem()" value="Add Item">
<input type="button" onclick="removeItem()" value="Remove Last Item">
<table>
<th>Name</th>
<tr>
<td>
<input type="text" id="input1" name="input1" />
</td>
<td>
<input type="hidden" id="input2" name="input2" />
</td>
</tr>
</table>
<input id="submit" type="submit" name="submit" value="Submit">
</form>
<script language="javascript">
function addItem() {
return false;
}
function removeItem() {
return false;
}
</script>
The function removeItem actually contains an error, which makes the form button do it's default behaviour (submitting the form). The javascript error console will usually give a pointer in this case.
Check out the function removeItem in the javascript part:
The line:
rows[rows.length-1].html('');
doesn't work. Try this instead:
rows.eq(rows.length-1).html('');
https://developer.mozilla.org/pt-BR/docs/Web/API/HTMLFormElement/submit_event
Do your logic on the form onsubmit event
submitter Read only
An HTMLElement object which identifies the button or other element which was invoked to trigger the form being submitted.
onsubmit="(evt) => console.log(evt)"
The event itself will bring along the caller and some usefull info.
Just use evt.preventDefault(); (default submit) evt.stopPropagation(); (submit bubbling) if the caller is a

Categories

Resources