How to prevent page refresh upon form.trigger('submit')? - javascript

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.

Related

How to trigger submitting form automatically and use preventDefault

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>

Confirm form submit with two buttons in BootboxJS

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.

Passing a Rails form POST data to a JS click event

I have a simple form where the user can edit their profile data and click "Submit"
I have an intercepting click event on the submit button so that I can run some arbitrary client-side validations before continuing with the submit.
$(function() {
$("body").on("click", "#user-profile input.submit", function(e) {
// Prevent the submit from continuing
e.preventDefault();
// Do some validation stuff here
//
//
// Assuming above was succesful, continue with original submit
$("#user-profile form.edit_user").submit();
});
});
I'd love to have access to the actual form data that was being POST-ed to the Submit button before I intercepted it. More specifically, the form contains several Rails nested attributes, so I'd love the data in the same nested format as well.
Are the form POST data params available here? Or am I stuck pulling data manually from the input fields using $("css.selector").val() ?
Thanks!
You can add listener to form event submit instead of click
$("body").on("submit", "form", function(e) {
var valid = true;
// Do some validation stuff here
//
//
if (!this.inputName.value) valid = false;
// Prevent the submit from continuing if invalid
if (!valid) e.preventDefault();
});
So if form elements are not valid e.preventDefault(); will prevent submitting, other way it will submit.

Two button confirmations - Jquery

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.

On submitting a form, check for a value that, if present, opos up a modal window for more info

I have a form that uses jQuery Validate. You click the Submit button, form gets validated and submitted via ajax. I want to add a step to this process.
I want to check for the presence of a value, say x. If x is NOT in the form I want to go ahead and submit it as I already do. If it IS in the form I want to open a modal window that requests further info THEN submits the form with that extra info added into the request.
Currently I can get the modal to trigger but then the form just continues with the submission. How do I get the form submission to pause while the modal is dealt with by the user?
jQuery Validate has a "success" option that is called after successful validation (which is when I want to check for triggering the modal) but that still doesn't pause execution.
In a nutshell: How do I validate a submitted form, check if the value x is present, if it is not present submit the form but if it is present pause the submission, pop up a modal window, let the user fill in some more data (and presumably click a "done" or "cancel" button of some sort), add that to the collected form data and then submit the lot? The pausing submission part has me stumped.
Use submit() on the first form...
$('#form1').submit(function() {
// The below validation goes in here
});
Validate it...
$("#form1").validate({
// Whatever rules you want to validate by
});
Check if the form is valid...
if($('#form1').valid()) {
// Branching on x, example below, will go in here
} else {
// It's not valid, stop the submission
return false;
}
Branch on x. If present, open the modal, if not return true to submit the form as is
if (x !== undefined) {
// Here is where you also need to pass the other form data to the modal
// append hidden text fields to the form and populate with the values
// Open your modal window, then stop the default submit process
$('#themodalwindow').openModal();
return false;
} else {
// No x so submit the form as is
return true;
}
Now you have to submit the form in the modal...
$('#form2').submit(function() {
return true;
});
If you appended the data collected in form1 to form2 then submitting the form will include everything you need. BTW, you can cache some stuff in that but this is the gist of it.
You can't pause a form submit, but you can cancel it if you return false on the form's onsubmit event. After you get your additional data from the modal window, simply add the data to the form and resubmit it via javascript.
Hook onto the form's submit function:
$('form').submit(function() {
if (x !== undefined) {
$('#dialog').show();
return false;
}
});

Categories

Resources