i have a form that when submitted, if any field is empty id like to prevent the submission and add a class to the field.
For some reason I cant seem to get it too work, Ive added a fiddle, can anybody point out where im goign wrong?
http://jsfiddle.net/yycqW/
There are a couple of problems with your fiddle. Firstly, you haven't closed the ready event handler. Secondly, are passing $this into jQuery which is undefined. You need to pass this instead.
Finally, the form is always going to be submitted because you have to actually stop the submission. You can call the preventDefault method of the event object to do so. Here's a new version of your code:
$(document).ready(function(){
$("#form").submit(function(e) {
$('input').each(function() {
if ($(this).val() == '') { //Pass this into jQuery, not $this
$(this).addClass('highlight');
e.preventDefault(); //Stop the form from submitting
}
});
});
});
Also note that it's unnecessary to use $(this).val() inside the each loop. this will be a reference to a DOM element, and that element will have a value property, so it's more efficient to simply use this.value.
You're not stopping the form from actually being submitted and thus it still gets posted (and thus immediately dropping your highlights). Try adding the preventDefault method to your form and manually submit after checking for errors.
Apart from not calling preventDefault, you are using $this instead of this in one place and the brackets don't match. Working version:
http://jsfiddle.net/yycqW/7/
$(document).ready(function() {
$("#form").submit(function(e, a) {
$('input, textarea', this).each(function() {
if (!$(this).val()) {
$(this).addClass('highlight');
e.preventDefault();
} else($(this).hasClass('highlight')) ? $(this).removeClass('highlight') : false; // remove class on valid
});
});
});
Rather than preventDefault(), returning false in the function that calls the form when submitted also prevents submitting. In the previous answer, let's think that there are more than one empty fields, preventDefault() will be unnecessarily fired more than once.
I would use something like this as a cleaner solution:
$(document).ready(function(){
$("#form").submit(function(e) {
var submit=true; //A flag that we'll return
$('input').each(function() {
if ($(this).val() == '') {
$(this).addClass('highlight');
submit=false //Setting the flag to false will prevent form to be submitted
}
});
return submit;
});
});
Related
I'm trying to disable all elements which has style display:none before submitting the form.
If there is e.preventDefault(), the form is not submitted at all and if there is no e.preventDefault() the infinite loop occures.
$(document).on('submit', 'form', function (e) {
e.preventDefault();
console.log($(':input:hidden').length);
$('#reservation-form > :input:hidden').attr("disabled", true);
$('#reservation-form').unbind('submit').submit();
});
Do you know what to do to make all display:none fields disabled before submitting this form?
You don't have to run $('#reservation-form').unbind('submit').submit();
Remove the e.preventDefault(); call and return true at the end of the function:
$(document).on('submit', 'form', function (e) {
console.log($(':input:hidden').length);
$('#reservation-form > :input:hidden').attr("disabled", true);
return true;
});
This should give you the behavior you want without having to bind and unbind events.
You are binding event to document level, so to unbind submit, you should unbind it at document level too.
That's said, the easiest method is to call instead DOM native submit() event:
$('#reservation-form')[0].submit();
BTW, for boolean attribute, better is to use .prop() even if in your case, it change nothing:
$('#reservation-form > :input:hidden').prop("disabled", true);
You are using the wrong selector to get the elements with input type hidden.
You should be using :
$('input[type=hidden]')
Documentation : Css Selectors
I have a button similar to below
<button id="uniqueId" onclick="runMethod(this)">Submit</button>
What I'm trying to do is stop the runMethod from running, until after I've done a check of my own. I've tried using the stopImmediatePropagation function, but this doesn't seem to have worked. Here's my jQuery:
$j(document).on('click', '#uniqueId', function(event) {
event.stopImmediatePropagation();
if(condition == true) {
// continue...
} else {
return false;
}
return false;
});
Note: runMethod basically validates the form, then triggers a submit.
What you want to do, especially in the way that you want to do it, requires a some sort of workaround that will always be a bit fiddly. It is a better idea to change the way the button behaves (e.g. handle the whole of the click event on the inside of the jQuery click() function or something along those lines). However I have found sort of a solution for your problem, based on the assumption that your user will first hover over the button. I am sure you can extend that functionality to the keyboard's Tab event, but maybe it will not work perfectly for mobile devices' touch input. So, bear in mind the following solution is a semi-complete workaround for your problem:
$(document).ready(function(){
var methodToRun = "runMethod(this)"; // Store the value of the onclick attribute of your button.
var condition = false; // Suppose it is enabled at first.
$('#uniqueId').attr('onclick',null);
$('#uniqueId').hover(function(){
// Check your stuff here
condition = !condition; // This will change to both true and false as your hover in and out of the button.
console.log(condition); // Log the condition's value.
if(condition == true){
$('#uniqueId').attr('onclick',methodToRun); // Enable the button's event before the click.
}
},
function(){
console.log('inactive'); // When you stop hovering over the button, it will log this.
$('#uniqueId').attr('onclick',null); // Disable the on click event.
});
});
What this does is it uses the hover event to trigger your checking logic and when the user finally clicks on the button, the button is enabled if the logic was correct, otherwise it does not do anything. Try it live on this fiddle.
P.S.: Convert $ to $j as necessary to adapt this.
P.S.2: Use the Javascript console to check how the fiddle works as it will not change anything on the page by itself.
Your problem is the submit event, just make :
$('form').on('submit', function(e) {
e.preventDefault();
});
and it works. Don't bind the button click, only the submit form. By this way, you prevent to submit the form and the button needs to be type button:
<button type="button" .....>Submit</button>
Assuming there's a form that is submitted when button is clicked.
Try adding
event.cancelBubble();
Hence your code becomes:
$j(document).on('click', '#uniqueId', function(event) {
// Don't propogate the event to the document
if (event.stopPropagation) {
event.stopPropagation(); // W3C model
} else {
event.cancelBubble = true; // IE model
}
if(condition == true) {
// continue...
} else {
return false;
}
return false;
});
Your code is mostly correct but you need to remove J:
$(document).on('click', '#uniqueId', function(event) {...
You also need to remove the onClick event from the inline code - there's no need to have it there when you're assigning it via jQuery.
<button id="uniqueId">Submit</button>
I have a form that I don't want to be submitted the first time submit is clicked, but the second time it should work like a normal submit. So I added a not-submittable class to the form on load, then after the first click remove that class... which should (I think) make it submit normally. But, this doesn't happen. The first click works as expected, removes the class and changes the button text. The second click, however, does the exact same thing. So, what am I missing here?
jQuery:
$('form#survey_7042 #ACTION_SUBMIT_SURVEY_RESPONSE').addClass('not-submittable');
$('form#survey_7042 #ACTION_SUBMIT_SURVEY_RESPONSE.not-submittable').click(function(event) {
$('form#survey_7042 #ACTION_SUBMIT_SURVEY_RESPONSE').removeClass('not-submittable');
$('form#survey_7042 #ACTION_SUBMIT_SURVEY_RESPONSE').val('Continue');
$('form#survey_7042 #ACTION_SUBMIT_SURVEY_RESPONSE').removeAttr('disabled');
return false;
});
Pre-javascript button:
<input type="submit" class="Button" value="Submit Survey" id="ACTION_SUBMIT_SURVEY_RESPONSE" name="ACTION_SUBMIT_SURVEY_RESPONSE">
Quote OP: "I have a form that I don't want to be submitted the first
time submit is clicked, but the second time it should work like a
normal submit."
Use jQuery .one() to block the submit on first click only.
http://api.jquery.com/one/
$('#ACTION_SUBMIT_SURVEY_RESPONSE').one('submit', function(e) {
e.preventDefault();
// do what you need to do on first click
}
Alternatively...
$('#ACTION_SUBMIT_SURVEY_RESPONSE').one('submit', function(e) {
e.preventDefault();
// do what you need to do on first click
if ( some-condition ) { // under certain conditions allow submit on first click
$(this).submit();
}
}
Instead of using .click(), try using the .on() and .off() methods to bind and unbind the event. In your case:
$('form#survey_7042 #ACTION_SUBMIT_SURVEY_RESPONSE.not-submittable').on("click.stopSubmit", function(event) {
$('form#survey_7042 #ACTION_SUBMIT_SURVEY_RESPONSE').removeClass('not-submittable');
$('form#survey_7042 #ACTION_SUBMIT_SURVEY_RESPONSE').val('Continue');
$('form#survey_7042 #ACTION_SUBMIT_SURVEY_RESPONSE').removeAttr('disabled');
if (...conditions are met.....) {
$('form#survey_7042 #ACTION_SUBMIT_SURVEY_RESPONSE.not-submittable').off("click.stopSubmit");
}
return false;
});
You may notice that the first parameter of the .on() method is the string representation of the handler, but that I appended the namespace ".stopSubmit". Namespacing your handlers allows you to unbind one specific click handler, rather than all click handlers. The best part about this is that if there is code in your original handler that you still want to use you can make a separate click handler to run that code, and it will not be unbound when you unbind the ".stopSubmit" handler.
Please note that .on() and .off() are the recommended bind/unbind methods - jQuery no longer recommends .bind() and .unbind().
UPDATE
After reading your comment about not unbinding until after certain conditions are met, I would would like to point out that you can insert the .off() call in a conditional. I have updated the code to reflect this.
You can do something like this
$(document).ready(function () {
$('#ACTION_SUBMIT_SURVEY_RESPONSE').click(function (event) {
if (!$('#ACTION_SUBMIT_SURVEY_RESPONSE').hasClass(".not-submittable")) {
//do all conditions you wish on first click
//if condidition meets add this class to button
$('#ACTION_SUBMIT_SURVEY_RESPONSE').addClass(".not-submittable");
//stop form submit
event.preventDefault();
}
else {
//calls when button have .not-submittable class may be second or any no of clicks
$('#ACTION_SUBMIT_SURVEY_RESPONSE').removeClass('not-submittable');
$('#ACTION_SUBMIT_SURVEY_RESPONSE').val('Continue');
$('#ACTION_SUBMIT_SURVEY_RESPONSE').removeAttr('disabled');
//commented return false so form submits normally
}
});
});
If there are certain criteria that must match use this where submitable contains your logic what makes it possible to send the form:
var submit = $('form#survey_7042 #ACTION_SUBMIT_SURVEY_RESPONSE');
submit.addClass('not-submittable');
submit.click(function(event) {
if (true == submitable) {
submit.removeClass('not-submittable').val('Continue').removeAttr('disabled');
submit.unbind();
event.preventDefault();
}
});
I have a button in my form. I need my form to be processed after the first click (or pressing Enter) on the button, and after that, if some conditions would be true, I do something like submitting the form by the second click or pressing Enter key on the button.
What do you think I have to do?
Create a (boolean) variable that saves your state, which is set to true when the first click (or action) has happened and your condition is true. Then submit on the second action when the variable is true.
If the condition has to be matched on both clicks (I guess so) consider the following:
$(function() {
var first = false;
$("form").submit(function() {
if(first && checkCondition())
submit();
if(!first && checkCondition())
first = true;
e.preventDefault();
});
});
so in basic code:
var answered = false;
$(function() {
$("form").submit(function() {
if(answered == false) {
answered = true;
return false;
}
});
});
If I've understood what you're trying to do correctly, you could bind an event handler to the submit event. That event handler will handle your validation, but if you use the jQuery one method, it will only be executed once. The next time the submit event is triggered, the form will submit as usual:
$("yourForm").one("submit", function(e) {
e.preventDefault(); //Stop the form from being submitted
//Do stuff
});
The result is effectively the same as #Manuel van Rijn's answer, but using jQuery's one just makes it a bit shorter and cleaner in my opinion. However, this could also add a slight performance benefit, as the event handler is unbound after it's execution and won't be called again.
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')