Code http://jsfiddle.net/Z9qP5/1/
I want to fadeOut my form after the user submitted their email. There is the next problem. I just can't catch the submit event, so what I want, if the success message appears, then the form should be hidden. I use :visible like this:
$('#mc-embedded-subscribe-form').submit(function (e) {
if($('#mce-success-response').is(':visible')){
$("#mc_embed_signup").hide();
}
});
#mce-success-response is the success dialog.
I also tried:
if( $("#mce-success-response").css('display') == 'block') {
}
but it doesn't work. What's wrong?
yes, I think the submit event is just a one way, you just submit, and you don't want to get response when you do like that way. maybe you can use ajax that can handle the result. actually, you just submit your form, then fade out your form I think.
This is more of a workaround, and not an effective solution.
But it works!
function checkSuccess() {
if ($('#mce-success-response').is(':visible')) {
$("#mc_embed_signup").hide();
}
}
window.setInterval(checkSuccess, 100);
You could also use the code below to add a delay to the hideing:
function checkSuccess() {
function successAction(){
$("#mc_embed_signup").hide();
}
if ($('#mce-success-response').is(':visible')) {
setTimeout(successAction, 2500);
}
}
window.setInterval(checkSuccess, 100);
One possible solution is to use a custom event in this case(because as I explained in the comment the success-respone element is displayed in an ajax success handler).
So in your mce_success_cb method
if (resp.result == "success") {
$('#mce-' + resp.result + '-response').show();
$('#mce-' + resp.result + '-response').html(resp.msg);
$('#mc-embedded-subscribe-form').each(function () {
this.reset();
});
$("#mc-embedded-subscribe-form").trigger('submitsuccess');
// If the form has errors, display them, inline if possible, or appended to #mce-error-response
} else {
//rest of your code
}
then
$(document).ready(function () {
$('#mc-embedded-subscribe-form').on('submitsuccess', function (e) {
$("#mc_embed_signup").hide();
});
});
Are you getting the success response from AJAX after the submit? As per your code snippet, I am assuming that to be the case and that the success boz appears once your Ajax request is completed. Since its going to be for a short while, you can try the following piece of code.
function waitForIt(){
if(!$('#mce-success-response').is(':visible')){
setTimeout(waitForIt(),500);
} else{
$("#mc_embed_signup").hide();
}
$('#mc-embedded-subscribe-form').submit(function (e) {
setTimeout(waitForIt(),500);
}
});
Alternatively, if its not the AJAX response that pops up the success message, you can try putting an interface between your form submit and the user action. Change your input type from submit to button or use a plain image as a button, i.e <img>. Use a click() instead of submit(), check if the container is visible, if yes, then hide the required container and trigger submit.
Hope it helps!
Related
I've got a different scenario of a submit button - submit the info if the response is correct, and throw an error if the response is incorrect.
First, I store the submit button onclick event in a variable and make it null, so it will not submit the info if the response is incorrect.
Here is my code:
(function() {
var submitBtn = jQuery('#submitConfigBtn')[0]
var submitBtnOnclick = submitBtn.onclick
submitBtn.onclick = null
jQuery('#submitConfigBtn').click(function() {
var btn = jQuery(this);
...ajax call,
success: function(response) {
if (response === 'badresponse') {
console.log('Bad response')
} else {
console.log('Response is ok')
btn.onclick = submitBtnOnclick
btn.click();
}
},
err: function(err) {
console.log(err)
}
});
})
})()
How I can retrieve the event from the variable and run it inside the onclick function?
From what I understood, you want to submit the form if the response is okay. No need to store the onclick event just to stop the form from submitting, you can either use: event.preventDefault(), or use type="button" instead in your button
I used the latter here, so instead of invoking the click event of the button, you need to use .submit() to the form, like this:
$(function() {
$('.submitConfigBtn').on('click', function() {
//ajax part here
//sample response result
let response = 'badresponse';
if (response === 'badresponse') {
console.log('Bad response')
} else {
console.log('Response is ok')
$('.sampleForm').submit();
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="sampleForm" action="" method="POST">
<button type="button" class="submitConfigBtn">Submit Config Button</button>
</form>
I would suggest you do some tricky logic.
Step 1.
Use two button
1. Submit type
2. Button type
Step 2.
Hide the submit button always.
Step 3.
if(response == true){
$("submitbtnid").trigger('click');
}
else {
console.log('write your custom logic');
}
If you want to avoid the "standard action" to happen you can call event.preventDefault() inside your click-handler function. There is no need to delete and re-install the on-click function itself.
Furthermore the jquery element btn will not know what to do with the property "onclick". This would be a property of a DOM object.
You are not the first person to come up with this problem ;-)
See here https://stackoverflow.com/a/14154017/2610061 for a possible solution.
(It looks like you have to know which action you want to defer, as there is no standard way of belatedly triggering any action that was initially prevented from happening. You can only trigger specific actions like .submit() of a form.)
I prepared a scenario that would work for your requirements. Please note that I do not capture the "click" event on the actual button but instead I listen for the "submit" event on the surrounding form. The form can be submitted by either clicking the button or by hitting the return key after filling out the input field. The current event handler will be executed in either case!
At first the default action is prevented from happening, then an asynchronous Ajax call is sent. Its success function in .done() carries out some "meaningful" test on the response and - depending on its outcome - will then trigger the form's submission or not. Should the Ajax call itself fail the .fail() function jumps into action and will do whatever is required ...
$(function() {
$('.validatedForm').on('submit', function(ev) {
ev.preventDefault(); // prevent submission before AJAX call
$.getJSON('http://jsonplaceholder.typicode.com/users/'+$('#q').val())
.done(function(da){
console.log(da);
if (da.address.city!=="Howemouth") { // some meaningful test on the result ...
setTimeout(()=>ev.target.submit(), 3000); // belated form submission!
console.log('Hey, the input was changed, in 3 seconds I will go to google!')
}})
.fail(function(da){console.log(da.status, da.statusText,'- Only user-IDs 1 ... 10 are allowed.');});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="http://google.com" class="validatedForm">
<input name="q" id="q" value="7">
<button>submit</button>
</form>
I have added an ajax validation to a textarea on my form, and initiate it using onblur in the html. However I have noticed that if I go to the submit the onblur event doesn't fire. Having read a lot of background I found a trick with setTimeout which I think ought to work by delaying the submit until after the blur. But I'm obviously doing something wrong or have misunderstood whats actually going on because its not working.
I have coded the following in a document ready block in a file read into my page in the footer:
$('button[type="submit"]').click(function(){
setTimeout(() => this,0);
$("#description").trigger('blur');
});
Can anyone see/explain my problem please?
As i understand you send text field value to the server with AJAX to validate it.
The function setTimeout wont help in your case. You have to wait for validation results first. And submit the form once validation result arrived.
So your code might look like this:
var isValid;
$("#description").on('blur', function(event){
isValid = false;
startValidation().then(function(){
isValid = true;
form.submit();
});
});
$('button[type="submit"]').on('click', function(event){
if (!isValid){
event.preventDefault();
return false;
}
});
Demo - jsfiddle.net/75CqW/
When someone clicks the Submit button, it shows the loading div even if the input is empty.
I don't want the user to see the #loading if he didn't write anything in the input, I've tried to add "required" in the input but the #loading is still showing when the input is empty. What do you think is wrong with my loading div?
Thanks in advance.
Instead of click handler use submit handler for the form - the form validation are triggered on form submit not on submit button click
$(function () {
$("#myform").submit(function () {
$("#controller").hide();
$("#loading").show();
});
});
Demo: Fiddle
Note: You might want to prevent the default action of submit event so that the default form submit is prevented - if you are using ajax to do server side processing
try this
var id = $("#statusid").val();
if (id.length == 0)
{
return false;
}
You need to test for a value (or run a validation check) on the field(s) before firing off the processing code
$(function() {
$(".submit").click(function() {
if $('#statusid').val() {
$("#controller").hide();
$( "#loading" ).show();
}
});
});
I have two forms on our site #footer_leads and #footer_leads2 and i have a live submit event but need to verify a few things before the form gets summitted so i have this code
$('#footer_leads2, #footer_leads').live('submit', function(e){
e.preventDefault();
console.log('again');
var form = $(this); //save reference to form
if(somevalidation){
form.die();
form.submit(); //submit form
}
I assumed the jQuery die event would do the trick like in the above example but the page just into an infinite loop and crashes my browser....any ideas on how to do this
From the jQuery die() page:
Note: In order for .die() to function correctly, the selector used
with it must match exactly the selector initially used with .live().
Try $('#footer_leads2, #footer_leads').die() instead.
You shouldn't need to remove the handler and resubmit. Just wait on the preventDefault() until you know whether or not the form passed validation:
$('#footer_leads2, #footer_leads').live('submit', function(e) {
if (!somevalidation)
e.preventDefault();
// Else, the form will continue submitting unimpeded.
});
Are you want to disable the form after the submit?
if yes, try this:
$('input[type=submit]', this).attr('disabled', 'disabled');
I hope its help,
Don't unbind/die.
Just submit the form with the native method.
$('#footer_leads2, #footer_leads').live('submit', function() {
if (true /* validation succeeded */ ) {
this.submit(); //submit form, but don't use jQuery's method
} else {
return false;
}
});
UPDATE:
Since it sounds like you're making an AJAX call for the validation, you could just do the this.submit() in the success: callback.
$('#footer_leads2, #footer_leads').live('submit', function() {
$.ajax({
url: 'some/path',
context: this, // set the context of the callbacks to the element
...
success: function( d ) {
if( d.is_valid ) {
this.submit();
} else {
// give some feedback to the user for validation failure
}
}
});
return false; // block the submit by default
});
From the docs ( http://api.jquery.com/die/ ) :
Note: In order for .die() to function correctly, the selector used
with it must match exactly the selector initially used with .live().
You need to use .unbind('submit')
i load a form into a jquery ui dialog. i have a submit button (inside my form - NOT the actual dialog buttons) that calls a controller action but i can't figure out how to close the dialog after the submit is called as i dont have any event handler that i am attaching.
is there anyway of doing this besides changing the submit to input type=button?
i know in jquery i can capture the submit
$('#positionForm').submit(function () {
// do stuff
return true;
});
but this seems to fire before submitting so i dont want to close the dialog yet.
is there anything wrong with the below code:
$('#positionForm').live('submit', function () {
$.post('/MyController/Action', $("#positionForm").serialize(), function (data) {
alert(data);
}, "html");
closeModalPopup();
return false ;
});
For updated question: You can call the close code in the success callback, like this:
$('#positionForm').live('submit', function () {
$.post('/MyController/Action', $(this).serialize(), function(data) {
$('#positionForm').closest(".ui-dialog-content").dialog("close");
}, "html");
return false;
});
Original Answer: You can attach a form submit handler, for example:
$("#myform").submit(function() {
$(this).closest(".ui-dialog-content").dialog("close");
});
You can give it a try here.
You can also do it using $("#name_of_the_dialog").dialog("close");
It's more natural than using $closest