Trigger form submit with multiple submit buttons - javascript

I have a form with two submit buttons, Rails backend expects to receive one of the button names (action1 or action2) in the params hash. I want to show "are you sure?" message on one of the buttons. I have this code:
<form action="/models" id="myform" method="post">
<input name="action1" id="action1Button" type="submit" value="Make Action 1">
<input name="action2" type="submit" value="Make Action 2">
</form>
$('#action1Button').click(function() {
$('#popup').modal('show');
// cancel a submit
return false;
});
$('#popupSubmitButton').click(function() {
$('#myform').submit(); // I want this to trigger action1
});
$('#popupCancelButton').click(function(){
$('#popup).modal('hide');
});
The problem is that when form submits there is no name of the submitted button in the request. Is there a way to submit a form as though as submit button was actually clicked?

Trigger the event with trigger(), and in the event handler you can actually check if the event was triggered or not by checking event.isTrigger
$('#action1Button').on('click', function(e) {
if (!e.isTrigger) {
$('#popup').modal('show');
return false;
}
});
$('#popupSubmitButton').on('click', function() {
$('#action1Button').trigger('click');
});
$('#popupCancelButton').on('click', function () {
$('#popup').modal('hide ');
});
FIDDLE

Related

Placeholder only appears for split second [duplicate]

I'm working on an ASP.net web application.
I have a form with a submit button. The code for the submit button looks like <input type='submit' value='submit request' onclick='btnClick();'>.
I want to write something like the following:
function btnClick() {
if (!validData())
cancelFormSubmission();
}
How do I do this?
You are better off doing...
<form onsubmit="return isValidForm()" />
If isValidForm() returns false, then your form doesn't submit.
You should also probably move your event handler from inline.
document.getElementById('my-form').onsubmit = function() {
return isValidForm();
};
Change your input to this:
<input type='submit' value='submit request' onclick='return btnClick();'>
And return false in your function
function btnClick() {
if (!validData())
return false;
}
You need to change
onclick='btnClick();'
to
onclick='return btnClick();'
and
cancelFormSubmission();
to
return false;
That said, I'd try to avoid the intrinsic event attributes in favour of unobtrusive JS with a library (such as YUI or jQuery) that has a good event handling API and tie into the event that really matters (i.e. the form's submit event instead of the button's click event).
Sometimes onsubmit wouldn't work with asp.net.
I solved it with very easy way.
if we have such a form
<form method="post" name="setting-form" >
<input type="text" id="UserName" name="UserName" value=""
placeholder="user name" >
<input type="password" id="Password" name="password" value="" placeholder="password" >
<div id="remember" class="checkbox">
<label>remember me</label>
<asp:CheckBox ID="RememberMe" runat="server" />
</div>
<input type="submit" value="login" id="login-btn"/>
</form>
You can now catch get that event before the form postback and stop it from postback and do all the ajax you want using this jquery.
$(document).ready(function () {
$("#login-btn").click(function (event) {
event.preventDefault();
alert("do what ever you want");
});
});
you should change the type from submit to button:
<input type='button' value='submit request'>
instead of
<input type='submit' value='submit request'>
you then get the name of your button in javascript and associate whatever action you want to it
var btn = document.forms["frm_name"].elements["btn_name"];
btn.onclick = function(){...};
worked for me
hope it helps.
This is a very old thread but it is sure to be noticed. Hence the note that the solutions offered are no longer up to date and that modern Javascript is much better.
<script>
document.getElementById(id of the form).addEventListener(
"submit",
function(event)
{
if(validData() === false)
{
event.preventDefault();
}
},
false
);
The form receives an event handler that monitors the submit. If the there called function validData (not shown here) returns a FALSE, calling the method PreventDefault, which suppresses the submit of the form and the browser returns to the input. Otherwise the form will be sent as usual.
P.S. This also works with the attribute onsubmit. Then the anonymus function function(event){...} must in the attribute onsubmit of the form. This is not really modern and you can only work with one event handler for submit. But you don't have to create an extra javascript. In addition, it can be specified directly in the source code as an attribute of the form and there is no need to wait until the form is integrated in the DOM.
You need to return false;:
<input type='submit' value='submit request' onclick='return btnClick();' />
function btnClick() {
return validData();
}
With JQuery is even more simple: works in Asp.Net MVC and Asp.Core
<script>
$('#btnSubmit').on('click', function () {
if (ValidData) {
return true; //submit the form
}
else {
return false; //cancel the submit
}
});
</script>
Why not change the submit button to a regular button, and on the click event, submit your form if it passes your validation tests?
e.g
<input type='button' value='submit request' onclick='btnClick();'>
function btnClick() {
if (validData())
document.myform.submit();
}
You need onSubmit. Not onClick otherwise someone can just press enter and it will bypass your validation. As for canceling. you need to return false. Here's the code:
<form onSubmit="return btnClick()">
<input type='submit' value='submit request'>
function btnClick() {
if (!validData()) return false;
}
Edit onSubmit belongs in the form tag.
It's simple, just return false;
The below code goes within the onclick of the submit button using jquery..
if(conditionsNotmet)
{
return false;
}
use onclick='return btnClick();'
and
function btnClick() {
return validData();
}
function btnClick() {
return validData();
}
<input type='button' onclick='buttonClick()' />
<script>
function buttonClick(){
//Validate Here
document.getElementsByTagName('form')[0].submit();
}
</script>

form onsubmit ignores action

I am new to JavaScript. I have a form with an action and I need to fill the form inputs using JavaScript on submitting. I use an onsubmit function which executes as expected, but the form didn't hit the action in the action attribute and no data is sent to the server.
Can anybody help me find what is missing ?
JavaScript/jQuery:
$("#myForm").submit(function (e) {
e.preventDefault();
return fillFormValues();
})
function fillFormValues()
{
$.get( ...,function( data ) {
//fill my inputs values here
return true;
});
return false;
}
HTML:
<form action="..." method="post" target="output_frame" id="myForm">
<input name="first" id="first" type="hidden" value="">
...
<input type="submit" value="next">
</form>
what you can do is prevent the jQuery event default that would submit the form, do the ajax and once values are set trigger the native submit event that will bypass the jQuery submit listener
$("#myForm").submit(function(e) {
e.preventDefault();
fillFormValues(this);
});
function fillFormValues(form) {
$.get(..., function(data) {
//fill your inputs values here
form.submit(); //trigger native submit which is not caught by jQuery
});
}

Form not submiting on chrome but in firefox submitting

I have a submmit button like Following:
Save & Continue
And My function in js is:
function checkCreditDebit(buttonValues) {
//Some validation here
//Disable Button if once clicked to prevent twice form submission
document.getElementById('saveandcontinue').disabled = 'disabled';
document.getElementById('onlysave').disabled = 'disabled';
}
But when i submit form in firefox it disabled the "save & continue", button and submit form. But in chrome it disable the button but not submit the form. What is the wrong with this please suggest. Thanks in Advance
Instead of just disabling your submit button(forms can also be submitted if you press enter on text-boxes), attach a handler to your form that will leave a 'class name' to your form as a mark that the form was already submitted, if the user submit the form again, the handler should check if the form has already the class name, then prevent duplicate submission via event.preventDefault().
try this:
<form onsubmit="prevent_duplicate(event,this);" action="">
<input type="text" />
<input type="submit" />
</form>
<script>
function prevent_duplicate(event,form)
{
if((" "+form.className+" ").indexOf(" submitted ") > -1)
{
alert("can't submit more than once!!!");
event.preventDefault();
}
else
{
form.classList.add("submitted");
}
}
</script>
Demo here
instead of disabling pervent multiple submit by setting a javascript flag example :
<form method="post" id="ecomFormBean" name="ecomFormBean" onsubmit="return checkSubmit(this);" >
<input type="text" />
<input type="submit" />
</form>
<script>
var formSubmitted = false;
function checkSubmit(f){
if (formSubmitted) {
alert('Please be patient. Your order may take 10 - 15 seconds to process. Thank you!');
return false;
}
else return formSubmitted = true;
}
</script>
Chrome runs javascript very fast. So it might be possible your checkCreditDebit(buttonValues) function which is to disable submit button executes before your php script submits the form.
I suggest you to call setTimeOut function before calling the javascript function so that the form can get submitted.
Give it a try.

In form data, pass info about which button was clicked -- after confirmation modal

The click event on my submit button triggers a confirmation modal.
When the user clicks on the confirmation button, the form is sent without the original submit button data, which I need.
Simplified code:
<form action="/action" method="post">
<!-- inputs -->
<button type="submit" name="foo" class="with-confirmation-modal" />
</form>
<script>
$(document).on('click', '.with-confirmation-modal', function() {
$form = $(this).closest('form');
$modal = $('#modal');
$modal.on('click', 'button[type=submit]', function() {
// form is sent without the info about which button
// was clicked prior to modal
$form.submit();
return false;
});
$modal.modal('show');
return false;
});
</script>
What's a good way to deal with this ?
When you post a form clicking on
<button type="submit" name="foo" />
data posted includes the name of the button :
...&foo=&...
This behaviour is broken by the confirmation popup. Here we simulate it by adding a hidden input with the name of the clicked button before calling $form.submit().
<script>
$(document).on('click', '.with-confirmation-modal', function() {
var $clickedBtn = $(this);
var $form = $clickedBtn.closest('form');
$modal = $('#credit-headsup-modal');
$modal.on('click', 'button[type=submit]', function() {
$(this).parent('.btn-wrapper').addClass('btn-wrapper--active');
$(this).siblings('.btn-loading').show();
// Pass info about which btn was clicked prior to modal
// by adding a hidden input with same name as btn
$form.append('<input type="hidden" name="'+$clickedBtn.attr('name')+'" value="">');
$form.submit();
return false;
});
$modal.modal('show');
return false;
</script>
If there is a better way, please share.

Javascript have to click button twice which is outside the form

Hi I am facing a problem on button click. I have a button outside the form due to some reason. On the click i have to validate the form and proceed to the next tab. But right now I have to click twice the button even if the form is valid. What's the issue right now?
script.js
<script>
$(document).ready(function () {
$('#step-2-form').submit(function(e)
{
var $as = $(this);
if($as.valid()){
e.preventDefault();
$('#dgstoneVariable').edatagrid('reload');
return document.getElementById('n.3').click();
}
if(!$as.valid()){
}
});
$('#step-2-form').validate({
rules: {
contactname2field: {
required: true
},
jobtitle2field: {
required: true
},
telephone2field: {
required: true
},
email2field: {
email: true,
required: true
},
cityfield: {
required: true
}
}
});
});
</script>
In registration.php I have three tab on 2nd tab I have a a structure as follows:
<form class="form-horizontal" id="step-2-form">
</form>
<form target="upload_target" id="fileupload" method="post" action="<?php echo site_url('upload_file/upload_it'); ?>" enctype="multipart/form-data">
....
....
//Here is a code of file upload. If the user browse and uploads the file then have to click continue button once to move onward. But if the user doesnt upload the files then he has to click the button twice to continue to step 3. (ANY IDEA ...???)
<button id="btnupload" style="padding: 4.5px; float:left;margin-top: 30px;border-radius: 0px;" disabled="disabled" type="submit" class="btn btn-primary btn-lg"><span class="glyphicon glyphicon-upload"></span></button>
</form>
<button form="step-2-form" type="submit" class="btn btn-success" id="tab-2-cont">CONTINUE</button>
The above button validtes the first form and then proceeds further. I have to place it outside because of the file uploading form.
I would suggest you to handle submit event
$(document).ready(function () {
$('#step-2-form').submit(function(e) {
var $as = $(this);
if(!$as.valid()){
e.preventDefault();
// Your error Message
}
});
});
To Associate button with your from you can use form attribute of button
The form element that the button is associated with (its form owner). The value of the attribute must be the id attribute of a element in the same document. If this attribute is not specified, the element must be a descendant of a form element. This attribute enables you to place elements anywhere within a document, not just as descendants of their elements.
So add form attribute. You don't need your button to be a descendant of a form element
<button form="step-2-form" id="tab-2-cont" type="submit" class="btn btn-success">CONTINUE</button>
A good read HTML5′s New “form” Attribute
Use .submit() mehtod to submit the form.
$(document).ready(function () {
$('#tab-2-cont').click(function() {
var $as = $('#step-2-form');
if($as.valid()){
$as.submit();
}
else
{
// alert("Not valid");
}
});
First when you put a submit button inside form. it will trigger submit event. So if you want to validate data before submit. prevent that event.
$(document).ready(function () {
$('#tab-2-cont').click(function(e) {
e.preventDefault();
var $as = $('#step-2-form');
if($as.valid()){
$as.submit();
}
else
{
// error messages
}
});
Your question is very unclear, Try this move your button inside your form.

Categories

Resources