I'm using Bootbox.js to show a confirmation box prior to submitting a form. The form has two submit buttons that handle two different actions. I was successful in showing the dialog and submitting the form, however the value of the button that was clicked is not included in the request. This is obvious, because by submitting the form manually no buttons were clicked. As I need to have a working form with and without javascript, I can't use hidden fields with a value changed at runtime by javascript. I then tried triggering the click event on the button itself when I leave the popup dialog, however I don't know how I could understand which button was originally clicked. Also, the click will probably trigger another submit event causing an infinite loop. How can I prevent that?
<form name="myform" action="myaction" method="post">
...
<button type="submit" name="decline" value="decline">Decline</button>
<button type="submit" name="accept" value="accept">Accept</button>
</form>
$(document).ready(function() {
$('form[name="myform"]').submit(function(e) {
bootbox.confirm({
message: '...',
callback: function(result) {
if (result) {
$('button[name="accept"]').click();
}
}
});
e.preventDefault();
}
});
An (admittedly brute-force) method of making your current script work is to create a sentinel variable that you toggle on the submission of your form:
$(function() {
var firstClick = true;
$('form[name="myform"]').submit(function(e) {
if(firstClick === true){
firstClick = false;
bootbox.confirm({
message: '...',
callback: function(result) {
if (result) {
$('button[name="accept"]').click();
}
}
});
e.preventDefault();
}
}
});
This lets you handle the form submission the first time the submit event is triggered, with subsequent submit events being allowed to submit the page.
It's also worth nothing (per the HTML spec) that
A button (and its value) is only included in the form submission if the button itself was used to initiate the form submission.
So your two buttons (Accept and Decline) could share the same name attribute, with only the button that was clicked reporting it's value.
Related
I have two ways of using form on a page.
First one is standard way when user types something in input field and clicks the submit button.
Second one is that the form is automatically filled and submitted depending on if a query string is passed to a page. (www.website.com/contact?fillform=true)
Everything works fine except I need yet to trigger the submit button for when query string is passed but currently it just refreshes the page.
I have done part in PHP, I have checked variables and they are ok.
Here is Codepen, e.preventDefault() is commented out since it doesn't work on window load
$(window).load(function() {
// Function for submitting form
function submitForm(e) {
console.log('I am in');
e.preventDefault();
jQuery.ajax({
... // Submit form
})
}
// Normal way of submitting form, works ok
$contactForm.on('submit', function(e) {
submitForm(e);
});
// This should trigger form automatically
if(fillFormAutomatically) {
// Everything so far works ok
// I just need to trigger form without page refresh but none of these works
$submitBtn.trigger('click');
$submitBtn.triggerHandler('click');
$contactForm.submit(e);
$contactForm.submit(function(e) {
console.log(e); // nothing in console shows here
submitForm(e);
});
submitForm(); // This triggers function but I can't pass event?
}
});
I think there is a couple of problems.
.load() was depreciated in jQuery 1.8, so don't use that. See: https://api.jquery.com/load-event/
Secondly, when you call submitForm() on window.ready(), there is no event. So you're trying to call .preventDefault() on undefined. Just move it to the .submit() function.
Does that answer your question?
$(window).ready(function() {
var $form = $("#form");
var $submitBtn = $("#submitBtn");
// Send form on window load
submitForm();
// Normal way
$form.submit(function(e) {
e.preventDefault();
submitForm(e);
});
// Send form
function submitForm() {
$('#vardump').append('Sending form...');
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" id="form">
<input type="text" value="Somedata">
<button id="submitBtn">Submit</button>
</form>
<div id="vardump"></div>
I have the following code which works well when triggered by the user clicking on the form's submit button:
// load dashboards when filter form is submitted
$('div.active form.filter-form').submit(function (e) {
// get submitted values
submittedData = $(this).serializeArray();
getDashboardURL();
e.preventDefault();
});
However whenever I try to trigger the form submission in the snippet below, it results in the page refreshing:
// trigger reload of dashboard
$('select.filter').change(function () {
$('select#'+this.id).val($(this).val());
$('div.active form.filter-form').trigger('submit');
});
How can I prevent the form submission (triggered by the select change event) from refreshing the page?
You can simply put return false on your markup of form.
<form onsubmit="function(); return false;">
Otherwise changing the button type to "button" instead of "submit" also should work.
I'm using a bootstrap validator from (https://github.com/1000hz/bootstrap-validator/blob/master/js/validator.js) and I'm trying to instantly display a modal 'loading' box when the submit button is pressed on a form. I've achieved this by doing the following:
$('form').on('submit', function (event) {
showLoadingModal();
if (!event.isDefaultPrevented()) {
event.preventDefault();
submitForm(this);
} else {
hideLoadingModal();
}
});
However I'm getting a problem where there is a small gap of time (under a second) between clicking the button and the modal being displayed. I'm assuming this delay is caused by the time taken validating all the fields on the form of which there are quite a lot.
This therefore leads me to believe that the validator 'form submit' is being executed before my code and I should be doing something different to call the showLoadingModal()
Edit:
I've added some logging into the js to work out what happens and when. I've also moved the showLoadingModal() into a 'button clicked' event to ensure it happens before form submit. Here's the order my messages get displayed:
button clicked
before show modal
after show modal
form submitted
about to validate
<--Modal appears now-->
set a delay of 300ms before submitting your form
var event;
var formobj;
('form').on('submit', function (event) {
showLoadingModal();
event = event; //save event to be used later
formobj = this;
setTimeout(function()
{
if (!event.isDefaultPrevented()) {
event.preventDefault();
submitForm(formobj );
} else {
hideLoadingModal();
}
},300);
return false; //Prevent normal submission of the form so that the dialog box is visible
});
I am assuming submitForm(this) is the function that does the form posting causing the page to reload
Just a thought, hope it helps!
Currently I have a submit button that pops up a confirmation that allows the form data to be processed or not.
I need my other button on my form page called "Cancel" to have the same action. How could I expand this code to add a second confirmation to the same form?
these are my buttons on the form :
And this is my current code that works :
</script>
<script>
$(document).on('submit', "#signinform", function(e)
{
if (!confirm("By clicking 'OK' you will be placed in queue! Please take a seat."))
{
e.preventDefault();
return;
}
});
</script>
just to add on :
The submit is a submit BUTTON. the Cancel is just a href with a border around it.
also again
This works at the moment for just the submit button.
I need my other button on the form called "Cancel" to do the samething, as in if you hit Ok your submission data will be deleted, and then you will be returned back to the form. If you hit cancel then you will remain on the page.
I guess you simply need something like
$(document).on('click', "#cancelButtonID", function(e)
{
if (!confirm("By clicking 'OK' you cancel the submission and the form is cleared."))
{
e.preventDefault();
return;
}
else {
//Clear the form or perform whatever actions are needed
}
});
I think however that you may want to replace your cancel link with a proper <input type="reset"> button, as that will clear the form automatically when you let the default action happen. Then you should be able to get rid of the else section above.
Quick question: How do i check if a submit button is clicked in a function.
explained question:
ok, so I have a validate script for my sign-up page. The validate function is run onblur of every input (after the submit button has been clicked first).
However, the validate script not only gives the inputs a red background if the correct information hasn't been entered, but it also displays an alert message.
My problem is: I only want to display the alert message if the submit button is clicked, otherwise i just want to do change the background color. So how do I check if a submit buttons is clicked, in a function.
I could just have two different functions, one to be run for all the inputs. and one to be run for the submit button.
Register the submit event to your form to validate before it is submitted.
Added: You should register the function in document ready event.
$(function(){
$("#myformid").submit(function()
{ if(!highlightNshowError())//your function to validate the form, return false if validation failed
return false; //stop submitting the form
else
return true;
});
});
or simply
$(function(){
$("#myformid").submit(function()
{
return highlightNshowError();
});
});