How to submit form with Javascript - javascript

<input type="submit" name="submit" value="Submit" onclick="check_form();"></div>
If all fields are corrects function check_form() return true, I want submit form, only hwen all fields are correct, how to do it. On this moments when I close JavaScript alerts form auto submit.

You are missing the return
<input type="submit" name="submit" value="Submit" onclick="return check_form();"></div>
and your function
function check_form(){
var isValid = true;
if(.....) {
isValid = false;
}
return isValid;
}
better yet use onsubmit of the form since an Enter key in a textbox can submit it.

Related

Skip validation when form timed out

I need the form to be automatically submitted when timed out,
but seems the form is still checking for the validation even when timed out.
How can I skip the validation and submit the form once time up.
(The validateForm function is checking all the radio button is checked.)
<input type="submit" name="submit" value="Submit" onclick="return validateForm()"/>
if(secs == 0 )
{
document.forms["test_form"].submit();
}
One simple way can be having two submit buttons.
One with the validation:
<input type="submit" name="submit" value="Submit" onclick="return validateForm()"/>
Other without validation with display none property:
<input type="submit" id="force_submit" style="display:none;" name="timeout_submit" value="Submit"/>
Then on timeout click the force_submit button:
if(secs == 0 )
{
document.getElementById('force_submit').click();
}

function in onsubmit not executing in javascript form

Whenever I press the submit button it just submits the form and doesn't seem to run the checkSubmit function. Everything I've looked at in other examples suggests my code is correct. Is there something missing or wrong with the way I'm calling it?
<script language="javascript" type="text/javascript">
function checkSubmit() {
alert("This is an alert!");
if (document.getElementById("userID").value.length <1) {
alert("Please enter a User ID.");
return false;
}
else {
alert(document.getElementById("userID").value.length)
return true;
}
</script>
<form name="submitform1" method="POST" action="http://127.0.0.1/MyFile.php" onsubmit="return checkSubmit();">
Enter User ID: <input id="userID" name="userID" type=text size="25"/><br />
<input type="submit" name="submit" onclick="this.form.onsubmit();" value="Submit" >
</form>
<br />
Your code is missing the closing curly bracket for the checkSubmit() function for one.
In your HTML change the remove the onsubmit handler from the form element and change the onclick attribute on the submit button to call the function:
onclick="checkSubmit(event);"
Then, in your function, prevent the form from submitting, do your checks, then submit the form.
function checkSubmit(e) {
e.preventDefault();
// do checks
document.submitform1.submit();
}

How to disable form validation for some submit button?

In my jsp form page, I have two submit button "Save" and "Cancel". When I click on both buttons it validates the form. I tried to put keyword "formnovalidate" for cancel button. But its not working.
Here I mentioned my button code:
<form id = "myForm" method="POST" onsubmit="return validateForm()" >
..........
<tr >
<td class="td_left"><input type="submit" value="save" onclick="form.action='${pageContext.servletContext.contextPath}/insert'"/></td>
<td class="td_right"><input type="submit" value="Cancel" onclick="form.action='${pageContext.servletContext.contextPath}/home'" formnovalidate /></td>
</tr>
................
</form>
Validations:
function validateForm() {
var x = document.forms["myForm"]["spcrId"].value;
if (x == null || x == "") {
alert("SPCR ID must be filled out");
return false;
}
}
What is the way to disable form validations for "Cancel" button?
I think the problem was because you, on the form's onsubmit attribute, placed a validation call. So, something like this should work without that onsubmit attribute:
<button name="action" class="btn btn-secondary" type="submit" value="Previous" formnovalidate="formnovalidate">Previous</button>
Try this:
<input type="submit" value="Cancel" onclick="this.form.setAttribute('novalidate', 'novalidate'); form.action='${pageContext.servletContext.contextPath}/home'" />
By setting the form's novalidate attribute on the click event you can bypass the validation for only that button.
Instead of type = "submit" you have to use
<input type="button" value="Cancel" />
or you can use
<button type="cancel" onclick="window.location='http://your.com';return
false;">Cancel</button>
try this
var myFormVar = document.myForm.FieldName.value;
if ((myFormVar == "") ) {
document.myForm.FieldName.value = '';
document.myForm.FieldName.focus();
alert ("alert here");
return;
}
You can use:-
`<button type="button"></button>`

Don't submit form after calling Javascript function

I have this problem:
my HTML code:
<form name="addUser" method="post" action="../src/process_register.php">
....
<button type="submit" onClick="formhash_register(this.form);">Submit</button>
</form>
my JavaScript code:
function formhash_register(form)
{
var username = form.inputUsername.value;
if(username == "")
return false;
else
form.submit();
}
Although my function returns false, you will go to another page, and thats not what I wanted.
Is there way to cancel submit process when the submit button is pressed ?
Try this:
<button type="submit"
onClick="return formhash_register(this.form);">Submit</button>
Change type to "button" which shouldn't automatically submit this form.
<button type="submit" onClick="formhash_register(this.form);">Submit</button>

How To Determine Which Submit Button Was Pressed, Form onSubmit Event, Without jQuery [duplicate]

This question already has answers here:
How can I get the button that caused the submit from the form submit event?
(22 answers)
Determine which element triggered a form submit event
(3 answers)
Closed 9 years ago.
This post was edited and submitted for review 1 year ago and failed to reopen the post:
Original close reason(s) were not resolved
I have a form with two submit buttons and some code:
HTML:
<input type="submit" name="save" value="Save" />
<input type="submit" name="saveAndAdd" value="Save and add another" />
JavaScript:
form.onSubmit = function(evnt) {
// Do some asynchronous stuff, that will later on submit the form
return false;
}
Of course the two submit buttons accomplish different things. Is there a way to find out in onSubmit which button was pressed, so later I could submit by doing thatButton.click()?
Ideally I would like to not modify the code for the buttons, just have a pure JavaScript addon that has this behavior.
I know that Firefox has evnt.explicitOriginalTarget, but I can't find anything for other browsers.
<form onsubmit="alert(this.submitted); return false;">
<input onclick="this.form.submitted=this.value;" type="submit" value="Yes" />
<input onclick="this.form.submitted=this.value;" type="submit" value="No" />
</form>
jsfiddle for the same
Not in the submit event handler itself, no.
But what you can do is add click handlers to each submit which will inform the submit handler as to which was clicked.
Here's a full example (using jQuery for brevity)
<html>
<head>
<title>Test Page</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
jQuery(function($) {
var submitActor = null;
var $form = $('#test');
var $submitActors = $form.find('input[type=submit]');
$form.submit(function(event) {
if (null === submitActor) {
// If no actor is explicitly clicked, the browser will
// automatically choose the first in source-order
// so we do the same here
submitActor = $submitActors[0];
}
console.log(submitActor.name);
// alert(submitActor.name);
return false;
});
$submitActors.click(function(event) {
submitActor = this;
});
});
</script>
</head>
<body>
<form id="test">
<input type="text" />
<input type="submit" name="save" value="Save" />
<input type="submit" name="saveAndAdd" value="Save and add another" />
</form>
</body>
</html>
Bare bones, but confirmed working, example:
<script type="text/javascript">
var clicked;
function mysubmit() {
alert(clicked);
}
</script>
<form action="" onsubmit="mysubmit();return false">
<input type="submit" onclick="clicked='Save'" value="Save" />
<input type="submit" onclick="clicked='Add'" value="Add" />
</form>
All of the answers above are very good but I cleaned it up a little bit.
This solution automatically puts the name of the submit button pressed into the action hidden field. Both the javascript on the page and the server code can check the action hidden field value as needed.
The solution uses jquery to automatically apply to all submit buttons.
<input type="hidden" name="action" id="action" />
<script language="javascript" type="text/javascript">
$(document).ready(function () {
//when a submit button is clicked, put its name into the action hidden field
$(":submit").click(function () { $("#action").val(this.name); });
});
</script>
<input type="submit" class="bttn" value="<< Back" name="back" />
<input type="submit" class="bttn" value="Finish" name="finish" />
<input type="submit" class="bttn" value="Save" name="save" />
<input type="submit" class="bttn" value="Next >>" name="next" />
<input type="submit" class="bttn" value="Delete" name="delete" />
<input type="button" class="bttn" name="cancel" value="Cancel" onclick="window.close();" />
Then write code like this into your form submit handler.
if ($("#action").val() == "delete") {
return confirm("Are you sure you want to delete the selected item?");
}
First Suggestion:
Create a Javascript Variable that will reference the button clicked. Lets call it buttonIndex
<input type="submit" onclick="buttonIndex=0;" name="save" value="Save" />
<input type="submit" onclick="buttonIndex=1;" name="saveAndAdd" value="Save and add another" />
Now, you can access that value. 0 means the save button was clicked, 1 means the saveAndAdd Button was clicked.
Second Suggestion
The way I would handle this is to create two JS functions that handle each of the two buttons.
First, make sure your form has a valid ID. For this example, I'll say the ID is "myForm"
change
<input type="submit" name="save" value="Save" />
<input type="submit" name="saveAndAdd" value="Save and add another" />
to
<input type="submit" onclick="submitFunc();return(false);" name="save" value="Save" />
<input type="submit" onclick="submitAndAddFunc();return(false);" name="saveAndAdd" value="Save and add
the return(false) will prevent your form submission from actually processing, and call your custom functions, where you can submit the form later on.
Then your functions will work something like this...
function submitFunc(){
// Do some asyncrhnous stuff, that will later on submit the form
if (okToSubmit) {
document.getElementById('myForm').submit();
}
}
function submitAndAddFunc(){
// Do some asyncrhnous stuff, that will later on submit the form
if (okToSubmit) {
document.getElementById('myForm').submit();
}
}
OP stated he didn't want to modify the code for the buttons. This is the least-intrusive answer I could come up with using the other answers as a guide. It doesn't require additional hidden fields, allows you to leave the button code intact (sometimes you don't have access to what generates it), and gives you the info you were looking for from anywhere in your code...which button was used to submit the form. I haven't evaluated what happens if the user uses the Enter key to submit the form, rather than clicking.
<script language="javascript" type="text/javascript">
var initiator = '';
$(document).ready(function() {
$(":submit").click(function() { initiator = this.name });
});
</script>
Then you have access to the 'initiator' variable anywhere that might need to do the checking. Hope this helps.
~Spanky
I use Ext, so I ended up doing this:
var theForm = Ext.get("theform");
var inputButtons = Ext.DomQuery.jsSelect('input[type="submit"]', theForm.dom);
var inputButtonPressed = null;
for (var i = 0; i < inputButtons.length; i++) {
Ext.fly(inputButtons[i]).on('click', function() {
inputButtonPressed = this;
}, inputButtons[i]);
}
and then when it was time submit I did
if (inputButtonPressed !== null) inputButtonPressed.click();
else theForm.dom.submit();
Wait, you say. This will loop if you're not careful. So, onSubmit must sometimes return true
// Notice I'm not using Ext here, because they can't stop the submit
theForm.dom.onsubmit = function () {
if (gottaDoSomething) {
// Do something asynchronous, call the two lines above when done.
gottaDoSomething = false;
return false;
}
return true;
}
Why not loop through the inputs and then add onclick handlers to each?
You don't have to do this in HTML, but you can add a handler to each button like:
button.onclick = function(){ DoStuff(this.value); return false; } // return false; so that form does not submit
Then your function could "do stuff" according to whichever value you passed:
function DoStuff(val) {
if( val === "Val 1" ) {
// Do some stuff
}
// Do other stuff
}

Categories