prevent postback using jquery,javascript - javascript

Here is my HTML code
<form id="form1" runat="server">
<input id="q" required />
<input id="btn" type="submit" value="Search" />
</form>
I'm trying the HTML 5 required feature in asp.net. The above code works. But a post back also occurs. Is there a way to prevent the post back using JavaScript, jQuery or any other method? I tried to prevent the post back using jQuery
$(document).ready(function () {
$('#btn').click(function (evt) {
evt.preventDefault();
});
});
But this makes the required validation not to fire.
Note: There are more than one button in the form.

change "click" event to "submit", and bind it not to btn but to form
$(document).ready(function () {
$('#form1').on("submit", function (evt) {
evt.preventDefault();
});
});

Here is the updated JsFiddle which has two inputs (one is required) and two buttons (one is submit).
HTML:
<form id="form1" method="get" action="http://example.com">
<input id="q" required />
<input id="w" />
<input id="btn" type="button" value="Cancel" />
<input id="btn" type="submit" value="Submit" />
Javascript
$('#form1').on("submit", function (evt) {
evt.preventDefault();
});
If that doesn't answer your question, please elaborate

Related

How to run form action and click event simultaneously on button click

I am having a form like this
<form name="test" action="action.php" method="get">
<input type="text" />
<input type="button" value="download"/></form>
I need a click event for download button. Eg. If i click download it should submit as action.php and run $('#button').click(function(){ also. How can I do it.
Perform the operation on 'download' button click then trigger the form submit using trigger
$('.download').click(function(e){
alert('downloading!') //Your Download Logic HERE
$(this).parent().trigger('submit')//Trigger Form SUBMIT ONCE THE OPERATION IS DONE
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="test" action="action.php" method="get">
<input type="text" />
<input type="button" value="download" class="download"></form>
Firstly note that <form> elements are not self closing, so your current HTML is invalid; the input elements need to be within the form itself.
Once that is fixed you can trigger() a submit event on the parent form to the #button element, like this:
$('#button').click(function() {
console.log('Custom logic here...');
$(this).closest('form').trigger('submit');
});
$('form').on('submit', function(e) {
e.preventDefault();
console.log('Submitting form...');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form name="test" action="action.php" method="get">
<input type="text" />
<input type="submit" value="search" />
<input type="button" value="download" id="button" />
</form>
You can simply submit your form by javascript, after clicking download button:
$('#button').click(function(){
...
document.forms["myform"].submit();

Detecting the appropriate button with javascript

I have a form with two buttons -
<form:form id="reviewApprvDisapprvForm" modelAttribute="updateProofingForm" method="post">
<input id="approveButton" onclick="submitForm()" type="image" src="/images/buttons/samplesApprovedButton.png" />
<br />
<input id="disapproveButton" onclick="submitForm()" type="image" src="/images/buttons/samplesNotApprovedButton.png" />
</form>
Here one button is for approve and another button for disapprove. I have a Javascript function "submitForm()" which is called "onclick" of these button. The function is like this
function submitForm(){
//if('approvedButton' is clicked){
$("#reviewApprvDisapprvForm").attr("action","/secure/userMgmt/roleBasedProofing/updateProofingConfirmMVC.do");
//}
$("#reviewApprvDisapprvForm").submit();
}
In this function I have set the action with javascript. Here, I am trying to find for which button click the "submitForm()" method is called. There are two buttons - "approveButton" and "disapproveButton". How can I do this, can anyone help me?
Thanks in advance
I would do it like this:
Remove the onclick="" from the HTML, set the image inside the input element, add the action to the form directly:
<form:form id="reviewApprvDisapprvForm" action="/secure/userMgmt/roleBasedProofing/updateProofingConfirmMVC.do" modelAttribute="updateProofingForm" method="post">
<input id="approveButton" type="submit"><img src="/images/buttons/samplesApprovedButton.png"/></input>
<br />
<input id="disapproveButton" type="image" src="/images/buttons/samplesNotApprovedButton.png" />
</form>
$(document).ready(function() {
$('#disapproveButton').click(function(){
//your disapprove logic here
});
});
This can help
<form:form id="reviewApprvDisapprvForm" modelAttribute="updateProofingForm" method="post">
<input id="approveButton" onclick="submitForm('approve')" type="image" src="/images/buttons/samplesApprovedButton.png" />
<br />
<input id="disapproveButton" onclick="submitForm('notApprove')" type="image" src="/images/buttons/samplesNotApprovedButton.png" />
</form>
and then
function submitForm(buttonVal){
if(buttonVal=='approve'){
$("#reviewApprvDisapprvForm").attr("action","/secure/userMgmt/roleBasedProofing/updateProofingConfirmMVC.do");
}
$("#reviewApprvDisapprvForm").submit();
}
Thanks

javascript function call for single form

I have multiple forms in my php file for different buttons. So, if I click on Back button, ramesh.php script should be called and so on. This is the code.
<form action="ramesh.php">
<input type="submit" value="Back" />
</form>
<form action="process.php" method="post">
<input name="rep_skyline" type="text" />
<input type="submit" />
</form>
<form action="update.php" method="post" >
<button type="submit">Update</button>
</form>
However, I need to pass some data to server from my client side on form submit just for the update button. I have a javascript function to send the data to server side as below.
<script type="text/javascript">
$(document).ready(function() {
$('form').submit(function(e) {
var mydata = 3;
if ($(this).is(':not([data-submit="true"])'))
{
$('form').append('<input type="hidden" name="foo" value="'+mydata+'">');
$('form').data('submit', 'true').submit();
e.preventDefault();
return false;
}
})
})
</script>
If I click on the update button, the javascript function is working fine. However, if I click on Back or Submit button, I should not be calling the javascript function. Is there someway to do this?
Give your form an id:
<form action="update.php" method="post" id="update-form">
Then use a more specific selector:
$("#update-form").submit(function() {
// Code
});
I'm not quite sure why you need JavaScript to dynamically add data to your form, however. You should just use an <input type="hidden" /> directly.
type=submit will always load the form's action. Try to specify wich form to submit.
<form name="backForm" id="backForm" action="ramesh.php">
<input type="submit" value="Back" />
</form>
<form name="form2" id="form2" action="process.php" method="post">
<input name="rep_skyline" type="text" />
<input type="submit" />
</form>
Now you can access the form via document.backForm or document.getElementById("backForm") and than use submit(); like document.getElementById("backForm").submit();

Can I determine which Submit button was used in javascript?

I have a very simple form with a name field and two submit buttons: 'change' and 'delete'. I need to do some form validation in javascript when the form is submitted so I need to know which button was clicked. If the user hits the enter key, the 'change' value is the one that makes it to the server. So really, I just need to know if the 'delete' button was clicked or not.
Can I determine which button was clicked? Or do I need to change the 'delete' button from a submit to a regular button and catch its onclick event to submit the form?
The form looks like this:
<form action="update.php" method="post" onsubmit="return checkForm(this);">
<input type="text" name="tagName" size="30" value="name goes here" />
<input type="hidden" name="tagID" value="1" />
<input type="submit" name="submit" value="Change" />
<input type="submit" name="submit" value="Delete" />
</form>
In the checkForm() function, form["submit"] is a node list, not a single element I can grab the value of.
Here's an unobtrusive approach using jQuery...
$(function ()
{
// for each form on the page...
$("form").each(function ()
{
var that = $(this); // define context and reference
/* for each of the submit-inputs - in each of the forms on
the page - assign click and keypress event */
$("input:submit", that).bind("click keypress", function ()
{
// store the id of the submit-input on it's enclosing form
that.data("callerid", this.id);
});
});
// assign submit-event to all forms on the page
$("form").submit(function ()
{
/* retrieve the id of the input that was clicked, stored on
it's enclosing form */
var callerId = $(this).data("callerid");
// determine appropriate action(s)
if (callerId == "delete") // do stuff...
if (callerId == "change") // do stuff...
/* note: you can return false to prevent the default behavior
of the form--that is; stop the page from submitting */
});
});
Note: this code is using the id-property to reference elements, so you have to update your markup. If you want me to update the code in my answer to make use of the name-attribute to determine appropriate actions, let me know.
You could also use the onclick event in a number of different ways to address the problem.
For instance:
<input type="submit" name="submit" value="Delete"
onclick="return TryingToDelete();" />
In the TryingToDelete() function in JavaScript, do what you want, then return false if do not want the delete to proceed.
Some browsers (at least Firefox, Opera and IE) support this:
<script type="text/javascript">
function checkForm(form, event) {
// Firefox || Opera || IE || unsupported
var target = event.explicitOriginalTarget || event.relatedTarget ||
document.activeElement || {};
alert(target.type + ' ' + target.value);
return false;
}
</script>
<form action="update.php" method="post" onsubmit="return checkForm(this, event);">
<input type="text" name="tagName" size="30" value="name goes here" />
<input type="hidden" name="tagID" value="1" />
<input type="submit" name="submit" value="Change" />
<input type="submit" name="submit" value="Delete" />
</form>
For an inherently cross-browser solution, you'll have to add onclick handlers to the buttons themselves.
<html>
<script type="text/javascript">
var submit;
function checkForm(form)
{
alert(submit.value);
return false;
}
function Clicked(button)
{
submit= button ;
}
</script>
<body>
<form method="post" onsubmit="return checkForm(this);">
<input type="text" name="tagName" size="30" value="name goes here" />
<input type="hidden" name="tagID" value="1" />
<input onclick="Clicked(this);" type="submit" name="submit" value="Change" />
<input onclick="Clicked(this);" type="submit" name="submit" value="Delete" />
</form>
</body>
</html>
You could use the SubmitEvent.submitter property.
form.addEventListener('submit', event => console.log(event.submitter))
Give each of the buttons a unique ID such as
<input type="submit" id="submitButton" name="submit" value="Change" />
<input type="submit" id="deleteButton" name="submit" value="Delete" />
I'm not sure how to do this in raw javascript but in jquery you can then do
$('#submitButton').click(function() {
//do something
});
$('#deleteButton').click(function() {
//do something
});
This says that if submitButton is clicked, do whatever is inside it.
if deleteButton is clicked, do whatever is inside it
In jQuery you can use $.data() to keep data in scope - no need for global variables in that case.
First you click submit button, then (depending on it's action) you assign data to form. I'm not preventing default action in click event, so form is submitted right after click event ends.
HTML:
<form action="update.php" method="post"">
<input type="text" name="tagName" size="30" value="name goes here" />
<input type="hidden" name="tagID" value="1" />
<input type="submit" name="submit" value="Change" />
<input type="submit" name="submit" value="Delete" />
</form>
JavaScript:
(function ($) {
"use strict";
$(document).ready(function () {
// click on submit button with action "Change"
$('input[value="Change"]').on("click", function () {
var $form = $(this).parents('form');
$form.data("action", "Change");
});
// click on submit button with action "Delete"
$('input[value="Delete"]').on("click", function () {
var $form = $(this).parents('form');
$form.data("action", "Delete");
});
// on form submit
$('form').on("submit", function () {
var $self = $(this);
// retrieve action type from form
// If there is none assigned, go for the default one
var action = $self.data("action") || "deafult";
// remove data so next time you won't trigger wrong action
$self.removeData("action");
// do sth depending on action type
if (action === "change") {
}
});
});
})(jQuery);
Right now you've got the same problem as you would a normal text input. You've got the same name on two different elements. Change the names to "Change" and "Delete" and then determine if either one of them were clicked by applying an event handler on both submits and providing different methods. I'm assuming you're using pure JavaScript, but if you want it to be quick, take a look at jQuery.
What you need is as simple as following what's on w3schools
Since you didn't mention using any framework, this is the cleanest way to do it with straight Javascript. With this code what you're doing is passing the button object itself into the go() function. You then have access to all of the button's properties. You don't have to do anything with setTimeout(0) or any other wacky functions.
<script type="text/javascript">
function go(button) {
if (button.id = 'submit1')
//do something
else if (button.id = 'submit2')
//do something else
}
</script>
<form action="update.php" method="post">
<input type="text" name="tagName" size="30" value="name goes here" />
<input type="hidden" name="tagID" value="1" />
<input id="submit1" type="submit" name="submit" value="Change" onclick="go(this);"/>
<input id="submit2" type="submit" name="submit" value="Delete" onclick="go(this);"/>
</form>
A click event anywhere in a form will be caught by a form's click handler (as long as the element clicked on allows it to propagate). It will be processed before the form's submit event.
Therefore, one can test whether the click target was an input (or button) tag of the submit type, and save the value of it (say, to a data-button attribute on the form) for processing in the form's submit handler.
The submit buttons themselves do not then need any event handlers.
I needed to do this to change a form's action and target attributes, depending upon which submit button is clicked.
// TO CAPTURE THE BUTTON CLICKED
function get_button(){
var oElement=event.target;
var oForm=oElement.form;
// IF SUBMIT INPUT BUTTON (CHANGE 'INPUT' TO 'BUTTON' IF USING THAT TAG)
if((oElement.tagName=='INPUT')&&(oElement.type=='submit')){
// SAVE THE ACTION
oForm.setAttribute('data-button',oElement.value);
}
}
// TO DO THE SUBMIT PROCESSING
function submit_form(){
var oForm=event.target;
// RETRIEVE THE BUTTON CLICKED, IF ONE WAS USED
var sAction='';
if(oForm.hasAttribute('data-button')){
// SAVE THE BUTTON, THEN DELETE THE ATTRIBUTE (SO NOT USED ON ANOTHER SUBMIT)
sAction=oForm.getAttribute('data-button');
oForm.removeAttribute('data-button');
}
// PROCESS BY THE BUTTON USED
switch(sAction){
case'Change':
// WHATEVER
alert('Change');
break;
case'Delete':
// WHATEVER
alert('Delete');
break;
default:
// WHATEVER FOR ENTER PRESSED
alert('submit: By other means');
break;
}
}
<form action="update.php" method="post" onsubmit="submit_form();" onclick="get_button();">
<input type="text" name="tagName" size="30" value="name goes here" />
<input type="hidden" name="tagID" value="1" />
<input type="submit" name="submit" value="Change" />
<input type="submit" name="submit" value="Delete" />
</form>
<p id="result"></p>
Here is my solution:
Just add dataset in submit button like this:
<form action="update.php" method="post" onsubmit="return checkForm(this);">
<input type="text" name="tagName" size="30" value="name goes here" />
<input type="hidden" name="tagID" value="1" />
<input type="submit" name="submit" value="Change" data-clicked="change" />
<input type="submit" name="submit" value="Delete" data-clicked="delete" />
</form>
In JS access it by:
$('body').on("submit", function(event){
var target = event.explicitOriginalTarget || event.relatedTarget || document.activeElement || {};
var buttonClicked = target.dataset['clicked'];
console.log(buttonClicked);
});
Name the delete button something else. Perhaps name one SubmitChange and name the other SubmitDelete.
I've been dealing with this problem myself. There's no built-in way to tell which button's submitting a form, but it's a feature which might show up in the future.
The workaround I use in production is to store the button somewhere for one event loop on click. The JavaScript could look something like this:
function grabSubmitter(input){
input.form.submitter = input;
setTimeout(function(){
input.form.submitter = null;
}, 0);
}
... and you'd set an onclick on each button:
<input type="submit" name="name" value="value" onclick="grabSubmitter(this)">
click fires before submit, so in your submit event, if there's a submitter on your form, a button was clicked.
I'm using jQuery, so I use $.fn.data() instead of expando to store the submitter. I have a tiny plugin to handle temporarily setting data on an element that looks like this:
$.fn.briefData = function(key, value){
var $el = this;
$el.data(key, value);
setTimeout(function(){
$el.removeData(key);
}, 0);
};
and I attach it to buttons like this:
$(':button, :submit').live('click', function () {
var $form = $(this.form);
if ($form.length) {
$form.briefData('submitter', this);
}
});

HTML form with two submit buttons and two "target" attributes

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

Categories