I have a form that uploads a file and targets an iframe on the page. When the user clicks submit, I want the file contents to "clear" out.
I tried this
$('#imageaddform').submit(function(){
$('#imagefile').val('');
});
But it clears the form before the submit, so nothing is ever uploaded.
Is how do I clear after submit?
If you have no other handlers bound, you could do something like this:
$('#imageaddform').submit(function(e) {
e.preventDefault(); // don't submit multiple times
this.submit(); // use the native submit method of the form element
$('#imagefile').val(''); // blank the input
});
Lonesomeday's solution worked for me but for Google Chrome I found it would still submit empty form data unless I added a timeout like this:
$('#imageaddform').submit(function(e) {
e.preventDefault(); // don't submit multiple times
this.submit(); // use the native submit method of the form element
setTimeout(function(){ // Delay for Chrome
$('#imagefile').val(''); // blank the input
}, 100);
});
You could do something like this:
$('#imageaddform').submit(function(){
setTimeout(function() {
$('#imagefile').val('');
},100);
});
How are u submitting the form? if this is normal form post then then page wont exist in that case i am wondering if u are looking to clear the form before the page refreshses so that when the user comes back he doesn't see the values populated.
If the form is submitted by ajax then you can
function(){
$('form1')[0].submit();
clearForm();
}
Did i miss the question?
Related
My contact form is not working correctly. When I enter wrong data, all is working as it should, but when data is correct the input fields are not showing. I need to click them with mouse and then they start showing.
This is what I have tried so far:
$('#submit_btn').click(function() {
if($('#register').find('.wpcf7-mail-sent-ok').length > 0){
$('#name-152').val('Full Name').show('slow');
$('#email-152').val('Email').show('slow');
$('#phone-152').val('Phone Number').show('slow');
}
});
please note that class .wpcf7-mail-sent-okappears only when form is filled submitted and correctly. What confuses me the most is that .find cannot find the descendant .wpcf7-mail-sent-ok, and it is one of the descendants.. I have tested it with console.log(); and alert();
This is Wordpress plugin - Contact Form 7
Any ideas?
The "Contact Form 7" plug-in acts on the submission event to do its magic, like manipulating styles and replacing the standard form submission behaviour by an AJAX-style submission.
As this might happen after the button's click event, and probably on the form's submit event, your code runs too soon.
One way to get around this, is to delay the execution of your code with setTimeout:
$('#submit_btn').click(function() {
setTimeout(function () {
if ($('#register').find('.wpcf7-mail-sent-ok').length) {
$('#name-152').val('Full Name').show('slow');
$('#email-152').val('Email').show('slow');
$('#phone-152').val('Phone Number').show('slow');
}
}, 100);
});
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
I'm using
$('#myform')[0].reset();
to clear HTML form fields when a clear button is clicked. I'm also using jquery.validate.js. So when the above runs, it triggers form validation. All form fields with any validation then display their error messages. How do I prevent this?
I have tried this but it didn't do anything:
$('#myform').removeAttr("nonvalidate");
From the question you linked, the answer is what you want... All you have to do is capture the reset event and call v.resetForm().
var v = $('form').validate(); //etc etc whatever you have here, the important part is saving "v"
$('form').on('reset',function () {
v.resetForm();
});
See it working here: http://jsfiddle.net/uuu8jerr/
I'm using asp.net MVC and when I submit a form, a previous developer had embedded some jQuery validation.
$('form').submit(function() {
...code done here to validate form fields
});
The problem is that both the "Save" and "Cancel" buttons on the form fire this submit jQuery function. I don't want the validation logic to fire if the "Cancel" input button was fired (id="cancel" name="cancel" value="cancel").
Is there a way that, within this submit function, I can retrieve the ID, name or value of which input button was pressed to submit the form?
I asked this same question: How can I get the button that caused the submit from the form submit event?
The only cross-browser solution I could come up with was this:
$(document).ready(function() {
$("form").submit(function() {
var val = $("input[type=submit][clicked=true]").val()
// DO WORK
});
$("form input[type=submit]").click(function() {
$("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
Not sure if its the answer you're looking for but you should change the "Cancel" button to an anchor tag. There's no need to submit a cancel unless you're doing work on the form values.
well this will only fire if the type of the input button is like so:
<input type='submit' ...
so make sure the cancel button does not have type='submit' and it should work
EDIT
This only works in FF and not in Chrome (and I so, I imagine, not in other WebKit based browsers either) so I'm just leaving this here as a browser specific workaround, an interesting note but not as the answer.
#Neal's suggestion of NOT making the cancel button of type submit is probably the cleanest way. However, if you MUST do it the way you are doing it now:
$('form').submit(function(e){
if(e.originalEvent.explicitOriginalTarget.id === 'cancel'){
//don't validate
}
else{
//validate
}
});
var myForm = $('form');
$('input[type="submit"]',myForm).click(function(e) {
var whoClickedsubmit = $(e.target); //further, you can use .attr('id')
//do other things here
});
EDIT
.submit(function(event){
var target = event.originalEvent.explicitOriginalTarget.value;
//But IE does not have the "explicitOriginalTarget" property
});
I keep getting duplicate entries in my database because of impatient users clicking the submit button multiple times.
I googled and googled and found a few scripts, but none of them seem to be sufficient.
How can I prevent these duplicate entries from occurring using javascript or preferably jQuery?
Thanx in advance!
How about disabling the button on submit? That's what I do. It works fine.
$('form').submit(function(){
$('input[type=submit]', this).attr('disabled', 'disabled');
});
Disclaimer:
This only works when javascript is enabled on the user's browser. If the data that's being submitted is critical (like a credit card purchase), then consider my solution as only the first line of defense. For many use cases though, disabling the submit button will provide enough prevention.
I would implement this javascript-only solution first. Then track how many duplicate records are still getting created. If it's zero (or low enough to not care), then you're done. If it's too high for you, then implement a back-end database check for an existing record.
This should do the trick:
$("form").submit(function() {
$(":submit", this).attr("disabled", "disabled");
});
No JQuery?
Alternatively, you can make a check from db to check if a record already exist and if so, don't insert new one.
One technique I've seen used is to assign a unique ID to every form that's opened, and only accept one submission per form based on the ID.
It also means you can check how many times people aren't bothering to submit at all, and you can check if the submission genuinely came from your form by checking if it's got an ID that your server created.
I know you asked for a javascript solution, but personally I'd do both if I needed the robustness.
Preventing the double posting is not so simple as disabling the submit button. There are other elements that may submit it:
button elements
img elements
javascripts
pressing 'enter' while on some text field
Using jQuery data container would be my choice. Here's an example:
$('#someForm').submit(function(){
$this = $(this);
/** prevent double posting */
if ($this.data().isSubmitted) {
return false;
}
/** do some processing */
/** mark the form as processed, so we will not process it again */
$this.data().isSubmitted = true;
return true;
});
Here is bit of jQuery that I use to avoid the double click problem. It will only allow one click of the submit button.
$(document).ready(function() {
$("#submit").on('click', function() {
});
});
I'm not sure what language/framework you're working with or if it's just straight HTML. But in a Rails app I wrote I pass a data attribute on the form button disable_with which keeps the button from being clickable more than once while the transaction is in process.
Here's what the ERB looks like.
<%= f.button "Log In", class: 'btn btn-large btn-block btn-primary', data: {disable_with: "<i class='icon-spinner'></i>Logging In..."} %>
This is what I came up with in https://github.com/liberapay/liberapay.com/pull/875:
$('form').on('submit', function (e) {
var $form = $(this);
// Check that the form hasn't already been submitted
if ($form.data('js-submit-disable')) {
e.preventDefault();
return false;
}
// Prevent submitting again
$form.data('js-submit-disable', true);
// Set a timer to disable inputs for visual feedback
var $inputs = $form.find(':not(:disabled)');
setTimeout(function () { $inputs.prop('disabled', true); }, 100);
// Unlock if the user comes back to the page
$(window).on('focus pageshow', function () {
$form.data('js-submit-disable', false);
$inputs.prop('disabled', false);
});
});
The problem with the method described here is that if you're using a javascript validation framework and the validation fails, you won't be able to correct and re-submit the form without refreshing the page.
To solve this, you need to plug into the success event of your validation framework and only then, set the submit control to disabled. With Parsley, you can plug into the form validated event with the following code:
$.listen('parsley:form:validated', function(e){
if (e.validationResult) {
/* Validation has passed, prevent double form submissions */
$('button[type=submit]').attr('disabled', 'disabled');
}
});
If you are using client-side validation and want to allow additional submit attempts if the data is invalid, you can disallow submits only when the form content is unchanged:
var submittedFormContent = null;
$('#myForm').submit(function (e) {
var newFormContent = $(this).serialize();
if (submittedFormContent === newFormContent)
e.preventDefault(true);
else
submittedFormContent = newFormContent;
});
Found at How to prevent form resubmission when page is refreshed (F5 / CTRL+R) and solves the problem:
<script>
if ( window.history.replaceState ) {
window.history.replaceState( null, null, window.location.href );
}
</script>
That is what I did to solve the problem.
I disabled the button for a second with adding setTimeout twice:
- the 1st time is to let the JS form fields verification work;
- the 2nd time is to enable the button in case if you have any verification on your back end, that may return an error, and hence the user will want to try to submit the form again after editing his data.
$(document).ready(function(){
$('button[type=submit]').on("click", function(){
setTimeout(function () {
$('button[type=submit]').prop('disabled', true);
}, 0);
setTimeout(function () {
$('button[type=submit]').prop('disabled', false);
}, 1000);
});
});