replace the submit button - javascript

I tried to implement a file upload process in my grid.
I chose to use the jquery.iframe-post-form plugin.
Most solutions post the data of the form and after the upload file.
In order to post all data of a form at once (Lastname, ...) + photo, I replaced the submit button of the form (sData) by mine.
$(formid).removeAttr('onsubmit');
$(formid).iframePostForm({ ... });
I attached code to this new button (click event). I changed the submit button id , so jqGrid will not attach its click event .
$('#sData').attr('id', 'mysubmit')
.click(function(e)
{
...
$(formid).submit();
})
Therefore I changed the behaviour of jqgrid: no beforeSubmit event, no afterSubmit event, no afterComplete event !
How to fire after all the afterSubmit event for getting back errors ?

How about just overriding the default behavior of the button?
Do your custom stuff the submit the form?
$(document).ready(function () {
$(":button").click(function (event) {
event.preventDefault();
//Do Stuff then submit the form
$('form').submit();
});
});

Related

How can I run jQuery script before form submit without using OnClientClick

I have an ASP.Net WebForms application where I am using jQuery validation. There are several buttons to submit the form, each with different options on the back end.
I have a custom validateForm() function that I can assign to the OnClientClick event of all the buttons, but I'm hoping for a more elegant solution where I don't have to specifically give each button the OnClientClick property.
So basically, is it possible to capture the $(form).submit() event before an asp button is submitted? Without using the OnClientClick attribute?
Solved: My issue was actually not because I couldn't catch the submit, but because the buttons were <a> links instead of inputs. I didn't realize this and made the post while at home trying to fix it from memory.
Any of the below solutions should work in the scenario above with actual submit buttons
Just attach a listener to the submit event:
$('form').on('submit', function (event) {
// Do whatever you need to do here ...
// You could also do `event.preventDefault();`,
// if you wanted to stop the submit.
});
You can use onsubmit event that will execute a JavaScript when a form is submitted from any button.
<form id="form1" runat="server" onsubmit="return ValidationFunction();">
And your JS function should return true or false as
function ValidationFunction() {
// Your jQuery validation
if (isValide) {
return true;
}
else {
return false;
}
}
Another option using JQuery to attaches an event handler to form submission
$(document).ready(function () { // << to make sure DOM is loaded
$('#form1').on('submit', function (e) {
e.preventDefault(); // << the default action of the event will not be triggered
var isValide = false;
if (isValide) {
alert('ok');
this.submit();
}
else {
alert('Not Valid');
}
});
});

Why won't this form submit with AJAX?

I'm trying to submit a form to Campaign Monitor. They offer this code example to POST via Ajax.
This is my code for my multi-step modal.
var next_step = false;
var final_step = false;
$('.next').on('click', function(e){
e.preventDefault();
if (next_step) {
$('#step-1').slideUp(function(){
$('#step-2').slideDown();
$('.next').html('Submit');// Change button text to submit
final_step = true;
});
}
next_step = true;
if (final_step) {
$('#myform').submit(function (e){
alert('submit started'); //This never fires unless I remove the preventDefault();
e.preventDefault();//But if I remove this, the page will refresh
$.getJSON(
this.action + "?callback=?",
$(this).serialize(),
function (data) {
if (data.Status === 400) {
alert('error');
} else {
alert('success');
}
})
});
}
});
On the last step of the form, I check whether final_step is true, if so, go ahead and submit the form via ajax.
The problem is that it just doesn't do anything? But if I remove the e.preventDefault(); from the $('#myform') it will post the form as normal and re-direct you to the form URL.
How can I fix this?
What you are doing currently is wiring up an onsubmit handler. Not invoking submit.
$('#myform').submit(function (e){ });
...is the same thing as...
<form action="#" method="post" onsubmit="return someFunction()">
... which is the same as ...
$('#myForm').on('submit', function(e){});
You are never submitting the form.
What you are looking for is to use Ajax to post the data to the server and not submit the form.
You can do that like this:
$.ajax({
type: "POST",
url: "SomeUrl.aspx",
data: dataString,
success: function() {
//display message back to user here
}
});
dataString would be replaced with the values you posting.
$('#myform').submit(function (e){
just registers an event handler and attaches it to the "submit" event of "myform", it doesn't actually cause a submit. It means you're saying you'd like this function to be run every time the form is submitted. This handler function should be outside your $('.next').on('click', function(e){ block. Just below it will do.
If, within the $('.next').on('click', function(e){ block you wish to cause the form to be submitted, write:
$('#myform').submit();
This will actually trigger the form submission.
See https://api.jquery.com/submit/ for more info on what the different method signatures of "submit" actually do.
This line: $('#myform').submit(function (e) { registers the function you pass as an argument as a handler to the submit event of the form, and does not invoke a submit action. I'm not sure whether or not this is the problem, though I would recommend preventDefault() outside of the wizard flow
(e.g.
$(document).ready(function() {
$("#form").submit(function(e) {
e.preventDefault();
}
});
)
Then inside the if(final_step) just do the post without worrying about the form.
Also, you'd do good in not setting a submit button inside the form if you do not wish to use it's functionality. Just create an element with a click event that sends the data rather than registering to the submit event of the form.
I'm not sure but I always do $('#form').submit() after click in element and catch this event (e.g. by $('#form').on('submit', function () { .. });) in other place.

Common jQuery to disable submit buttons on all forms after HTML5 validation

Please pardon me if it is a basic thing, because I am a new learner of Javascript/jQuery. I have been trying to disable submit button to disable multiple submits. I have come across multiple solutions here as well, but all those used specific form name. But I wanted to apply a global solution for all forms on all pages so I dont have to write code on each page, so I put this in footer, so all pages have:
$('input:submit').click(function(){
$('input:submit').attr("disabled", true);
});
This code works on all the forms in all pages as I wanted, but if there are HTML5 required fields in form and form is submitted without them, of course notifications are popped but button still gets disabled. So, I tried with this:
$('input:submit').click(function(){
if ($(this).valid()) {
$('input:submit').attr("disabled", true);
$('.button').hide();
});
});
But this does not work. Kindly help me so that jQuery only disables when all HTML5 validation is done. Thanks
Try this and let me know:
$('input:submit').click(function(){
if ($(this).closest("form").checkValidity()) {
$('input:submit').attr("disabled", true);
$('.button').hide();
});
});
Ruprit, thank you for the tip. Your example did not work for me (in Firefox), but it helped me a lot.
Here is my working solution:
$(document).on("click", ".disable-after-click", function() {
var $this = $(this);
if ($this.closest("form")[0].checkValidity()) {
$this.attr("disabled", true);
$this.text("Saving...");
}
});
Since checkValidity() is not a jQuery function but a JavaScript function, you need to access the JavaScript element, not the jQuery object. That's the reason why there has to be [0] behind $this.closest("form").
With this code you only need to add a class="disable-after-click" to the button, input, link or whatever you need...
It is better to attach a handler to the submit event rather than a click event, because the submit event is only fired after validation is successful. (This saves you from having to check validity yourself.)
But note that if a submit button is disabled then any value they may hold is NOT submitted to the server. So we need to disable the inputs after form submission.
The question is compounded by the new HTML5 attribute form which allows associated inputs to be anywhere on the page as long as their form attribute matches a form ID.
This is the JQuery snippet that I use:
$(document).ready( function() {
$("form").on("submit", function(event) {
var $target = $(event.target);
var formId = $target.attr("id");
// let the submit values get submitted before we disable them
window.setTimeout(function() {
// disable all submits inside the form
$target.find("[type=submit]").prop("disabled", true);
// disable all HTML5 submits outside the form
$("[form=" + formId + "][type=submit]").prop("disabled", true);
}, 2); // 2ms
});
});
---[ WARNING ]---
While disabling submit buttons prevents multiple form submissions, the buttons have the unfortunate side effect of staying disabled should the user click the [Back] button.
Think about this scenario, the user edits some text, clicks submit (and get redirected to different page to view the edits), clicks back to edit some more, ... and ... they can't re-submit!
The solution is to (re-)enable the submit button on page load:
// re-enable the submit buttons should the user click back after a "Save & View"
$(document).ready( function() {
$("form").each(function() {
var $target = $(this);
var formId = $target.attr("id");
// enable all submits inside the form
$target.find("[type=submit]").prop("disabled", false);
// enable all HTML5 submits outside the form
$("[form=" + formId + "][type=submit]").prop("disabled", false);
});
});
Try this
`jQuery('input[type=submit]').click(function(){ return true;jQuery(this).prop('disabled','disabled');})`
run this code on successful validation of the form

Jquery onClick-event for submit form in Chrome

I have a js-code:
$(document).on('click', '#form #submitForm', function(e){
$('#form').submit();
return false;
});
$(document).on('submit', '#form', function(e){
// ajax request on submit form
return false;
});
where #form is the id of form, #submitForm is the id of submit-button inside this form.
I use .on() because of fact that my form is dynamically generated by ajax requests on submit.
Some people with Google Chrome on Win7 complaints about this isn't working and by pressing #submitForm just redirect to "form action"-url occurs.
I have Google Chrome on Win7 and it's working perfectly.
Want do I missing or did wrong?
When you submit a form, this will redirect to the url action. If you dont want to redirect, you have to create an ajax that "submit " the form
What you need is to stop the default behaviour of form when submit button is pressed.
Change your code to this:
$(document).on('submit', '#form', function(e){
// ajax request on submit form
e.preventDefault();
e.stopPropogation();
return false;
});

Submit a form using onclick event, but only allow once

I am both setting a form's action and submitting the form via the onclick event of a div:
<div class="action_button" onclick="document.forms['test'].action='url/to/action';document.forms['test'].submit()">
<span class="action_button_label">Save</span>
</div>
This works fine, but I'm wanting to use some code that conditionally checks for the 'Save' in the action_label_button, and only lets the submit() fire once. I'm trying to prevent multiple saves (which is yielding duplicate data in my app) from occurring.
// disable save buttons onclick (prevent multiple clicks of save buttons)
$('.action_button_label').one('click', function() {
// if the button is a save button
if($(this).html().indexOf('Save') != -1) {
// submit the parent form
$(this).html('<span class="action_button_label" style="color:gray;">Saving...</span>');
$(this).parents('form').submit();
}
});
$('form').bind('submit', function() {
$(this).find('action_button').attr('onclick', '');
});
This code doesn't seem to work as I expected. I'm afraid I'm a bit out of my depth here, any pointers would be great.
Try replacing
$(this).find('action_button').attr('onclick', '');
with
$(this).find('.action_button').attr('onclick', '');
You should always handle multiple submits server side to ENSURE you don't get them. However you can hide the button-label to assist with this client side.
$('.action_button_label').one('click', function() {
// if the button is a save button
if($(this).html().indexOf('Save') != -1) {
// submit the parent form
$('.action_button_label').hide(); //ADD THIS
$(this).html('<span class="action_button_label" style="color:gray;">Saving...</span>');
$(this).parents('form').submit();
}
});
$('form').bind('submit', function() {
$(this).find('action_button').attr('onclick', '');
});

Categories