In a MVC view, I have a form as below. when user click on the submit button, I want to check somthing firstly. If it is ok, submit the form. If not pass the checking, give user a alert message, then stay in the view. My sample code as:
<script type="text/javascript">
function CheckingStatus() {
//.....
if (answer == "N") {
alert("You choose No.");
return false;
}
}
</script>
<% Html.RenderPartial("MyForm"); %>
....
<input id="btnSubmit" type="submit" value="Submit" onclick="CheckingStatus();" />
<% } %>
But when testing, even answer=="N", the form is still submitted. How to stop the form submitting ?
try changing
<input id="btnSubmit" type="submit" value="Submit" onclick="CheckingStatus();" />
to
<input id="btnSubmit" type="submit" value="Submit" onclick="return CheckingStatus();" />
Another way it can be done:
document.forms['MyForm'].onsubmit = CheckingStatus;
Change your code to:
<input id="btnSubmit" type="submit" value="Submit" onclick="return CheckingStatus();" />
Note I added the word "return".
I would use an ASP.NET button, OR add the runat="server" property to the HMTL button then use the UseSubmitBehavior="false" property to disable postback / form submission. You can then call form.Submit(); or similar in your JavaScript.
Related
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>`
I am trying to disable a button on click, as well as change the text of the button. here is my code:
<input type="submit" value="Register" name="submit" id="submit" onClick="javascript:replaceButtonText('submit', 'Please wait...'); document.form1.submit.disabled=true;">
What is happening, is the button gets disabled, and the text changes, but the form does not do anything (submit). what am I doing wrong?
This works:
<html>
<body>
<form name="form1" method="post" action="myaction">
<input type="text" value="text1"/>
<input type="submit" value="Register" name="submit" id="submit"
onclick="javascript: replaceButtonText('submit1', 'Please wait...'); document.form1.submit.disabled=true; return true; ">
</form>
</body>
</html>
Form controls with a name are made available as named properties of the form they are in using their name. So:
document.form1.submit
refers to the button, not the submit method.
Writing:
< ... onclick="javascript:..." ...>
means that "javascript" is treated as a useless label, just don't do it. If you want the button to become disabled and change its label when the form is submitted, then use something like:
<form>
<input name=foo value=bar>
<input type="submit" onclick="
this.value='Please wait...';
this.disabled = true;
var theForm = this.form;
window.setTimeout(function(){theForm.submit();},1);
">
</form>
and let the form submit normally.
Of course the function in the onclick attribute should be a function call rather than a slab of code, but you get the idea.
I have two buttons, and I want to apply one action to another. For example.
<form>
<input type="submit" />
</form>
<input type="submit" />
I want to make the second button submit the form, despite being outside of the form.
You should make them of type button, and give your form an id.
Markup:
<form id="myForm">
<---STUFF---->
<input type='button' id='otherButton'>
</form>
<input type='button' id='someButton'>
jQuery:
$('#someButton').click(function() { $('#myForm').submit(); });
$(':input:last').click(function()
{
$('form').submit();
});
// enable form submit on the second <input>
$('input[type=submit]').click(function(){
$('form').submit();
});
// disable the inner <input>
$('form input[type=submit]').click(function(){
return false;
});
Something like this should do your trick.
If you want the second button to do everything the first can do (not just submit), you can try something like this:
html
<form>
<input id="insideButton" type="submit" />
</form>
<input id="outsideButton" type="submit" />
jsJQUERY
$("#outsideButton").click(function() {
$("#insideButton").trigger("click");
});
you can using jQuery $("#test").click() if you have jQuery instead of the document... stuff below or the way below will work without jQuery
<form name="testForm1">
<input type="submit" id="test" />
</form>
<!-- use this when not in a form: -->
<button onclick="button1_click();" id="button1"></button>
In your head tag
<script type="text/javascript">
function button1_click(){
document.forms.testForm1.submit();
}
</script>
Changed for the users that put performance under clean code
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
}
I have one HTML <form>.
The form has only one action="" attribute.
However I wish to have two different target="" attributes, depending on which button you click to submit the form. This is probably some fancy JavaScript code, but I haven't an idea where to begin.
How could I create two buttons, each submitting the same form, but each button gives the form a different target?
I do this on the server-side.
That is, the form always submits to the same target, but I've got a server-side script who is responsible for redirecting to the appropriate location depending on what button was pressed.
If you have multiple buttons, such as
<form action="mypage" method="get">
<input type="submit" name="retry" value="Retry" />
<input type="submit" name="abort" value="Abort" />
</form>
Note: I used GET, but it works for POST too
Then you can easily determine which button was pressed - if the variable retry exists and has a value then retry was pressed, and if the variable abort exists and has a value then abort was pressed. This knowledge can then be used to redirect to the appropriate place.
This method needs no Javascript.
Note: This question and answer was from so many years ago when "wanting to avoid relying on Javascript" was more of a thing than it is today. Today I would not consider writing extra server-side functionality for something like this. Indeed, I think that in most instances where I would need to submit form data to more than one target, I'd probably be doing something that justified doing a lot of the logic client-side in Javascript and using XMLHttpRequest (or indeed, the Fetch API) instead.
It is more appropriate to approach this problem with the mentality that a form will have a default action tied to one submit button, and then an alternative action bound to a plain button. The difference here is that whichever one goes under the submit will be the one used when a user submits the form by pressing enter, while the other one will only be fired when a user explicitly clicks on the button.
Anyhow, with that in mind, this should do it:
<form id='myform' action='jquery.php' method='GET'>
<input type='submit' id='btn1' value='Normal Submit'>
<input type='button' id='btn2' value='New Window'>
</form>
With this javascript:
var form = document.getElementById('myform');
form.onsubmit = function() {
form.target = '_self';
};
document.getElementById('btn2').onclick = function() {
form.target = '_blank';
form.submit();
}
Approaches that bind code to the submit button's click event will not work on IE.
In case you are up to HTML5, you can just use the attribute formaction. This allows you to have a different form action for each button.
<!DOCTYPE html>
<html>
<body>
<form>
<input type="submit" formaction="firsttarget.php" value="Submit to first" />
<input type="submit" formaction="secondtarget.php" value="Submit to second" />
</form>
</body>
</html>
This works for me:
<input type='submit' name='self' value='This window' onclick='this.form.target="_self";' />
<input type='submit' name='blank' value='New window' onclick='this.form.target="_blank";' />
In this example, taken from
http://www.webdeveloper.com/forum/showthread.php?t=75170
You can see the way to change the target on the button OnClick event.
function subm(f,newtarget)
{
document.myform.target = newtarget ;
f.submit();
}
<FORM name="myform" method="post" action="" target="" >
<INPUT type="button" name="Submit" value="Submit" onclick="subm(this.form,'_self');">
<INPUT type="button" name="Submit" value="Submit" onclick="subm(this.form,'_blank');">
Simple and easy to understand, this will send the name of the button that has been clicked, then will branch off to do whatever you want. This can reduce the need for two targets. Less pages...!
<form action="twosubmits.php" medthod ="post">
<input type = "text" name="text1">
<input type="submit" name="scheduled" value="Schedule Emails">
<input type="submit" name="single" value="Email Now">
</form>
twosubmits.php
<?php
if (empty($_POST['scheduled'])) {
// do whatever or collect values needed
die("You pressed single");
}
if (empty($_POST['single'])) {
// do whatever or collect values needed
die("you pressed scheduled");
}
?>
Example:
<input
type="submit"
onclick="this.form.action='new_target.php?do=alternative_submit'"
value="Alternative Save"
/>
Voila.
Very "fancy", three word JavaScript!
Here's a quick example script that displays a form that changes the target type:
<script type="text/javascript">
function myTarget(form) {
for (i = 0; i < form.target_type.length; i++) {
if (form.target_type[i].checked)
val = form.target_type[i].value;
}
form.target = val;
return true;
}
</script>
<form action="" onSubmit="return myTarget(this);">
<input type="radio" name="target_type" value="_self" checked /> Self <br/>
<input type="radio" name="target_type" value="_blank" /> Blank <br/>
<input type="submit">
</form>
HTML:
<form method="get">
<input type="text" name="id" value="123"/>
<input type="submit" name="action" value="add"/>
<input type="submit" name="action" value="delete"/>
</form>
JS:
$('form').submit(function(ev){
ev.preventDefault();
console.log('clicked',ev.originalEvent,ev.originalEvent.explicitOriginalTarget)
})
http://jsfiddle.net/arzo/unhc3/
<form id='myForm'>
<input type="button" name="first_btn" id="first_btn">
<input type="button" name="second_btn" id="second_btn">
</form>
<script>
$('#first_btn').click(function(){
var form = document.getElementById("myForm")
form.action = "https://foo.com";
form.submit();
});
$('#second_btn').click(function(){
var form = document.getElementById("myForm")
form.action = "http://bar.com";
form.submit();
});
</script>
It is do-able on the server side.
<button type="submit" name="signin" value="email_signin" action="/signin">Sign In</button>
<button type="submit" name="signin" value="facebook_signin" action="/facebook_login">Facebook</button>
and in my node server side script
app.post('/', function(req, res) {
if(req.body.signin == "email_signin"){
function(email_login) {...}
}
if(req.body.signin == "fb_signin"){
function(fb_login) {...}
}
});
Have both buttons submit to the current page and then add this code at the top:
<?php
if(isset($_GET['firstButtonName'])
header("Location: first-target.php?var1={$_GET['var1']}&var2={$_GET['var2']}");
if(isset($_GET['secondButtonName'])
header("Location: second-target.php?var1={$_GET['var1']}&var2={$_GET['var2']}");
?>
It could also be done using $_SESSION if you don't want them to see the variables.
Alternate Solution. Don't get messed up with onclick,buttons,server side and all.Just create a new form with different action like this.
<form method=post name=main onsubmit="return validate()" action="scale_test.html">
<input type=checkbox value="AC Hi-Side Pressure">AC Hi-Side Pressure<br>
<input type=checkbox value="Engine_Speed">Engine Speed<br>
<input type=submit value="Linear Scale" />
</form>
<form method=post name=main1 onsubmit="return v()" action=scale_log.html>
<input type=submit name=log id=log value="Log Scale">
</form>
Now in Javascript you can get all the elements of main form in v() with the help of getElementsByTagName(). To know whether the checkbox is checked or not
function v(){
var check = document.getElementsByTagName("input");
for (var i=0; i < check.length; i++) {
if (check[i].type == 'checkbox') {
if (check[i].checked == true) {
x[i]=check[i].value
}
}
}
console.log(x);
}
This might help someone:
Use the formtarget attribute
<html>
<body>
<form>
<!--submit on a new window-->
<input type="submit" formatarget="_blank" value="Submit to first" />
<!--submit on the same window-->
<input type="submit" formaction="_self" value="Submit to second" />
</form>
</body>
</html>
On each of your buttons you could have the following;
<input type="button" name="newWin" onclick="frmSubmitSameWin();">
<input type="button" name="SameWin" onclick="frmSubmitNewWin();">
Then have a few small js functions;
<script type="text/javascript">
function frmSubmitSameWin() {
form.target = '';
form.submit();
}
function frmSubmitNewWin() {
form.target = '_blank';
form.submit();
}
</script>
That should do the trick.
e.submitEvent.originalEvent.submitter.value
if you use event of form