I'm trying to add some validation to a form. I have a jQuery function that is doing exactly what I want:
jQuery('#post').submit(function() {
if (jQuery("#set-post-thumbnail").find('img').size() > 0) {
jQuery('#ajax-loading').hide();
jQuery('#publish').removeClass('button-primary-disabled');
return true;
}else{
alert("Please set a Featured Image!");
jQuery('#ajax-loading').hide();
jQuery('#publish').addClass('button-primary-disabled');
return false;
}
return false;
});
However, I want to change it so that this function only runs if a radio button elsewhere on the page is selected. So I tried this:
if (jQuery('#top').checked) {
jQuery('#post').submit(function() {
if (jQuery("#set-post-thumbnail").find('img').size() > 0) {
jQuery('#ajax-loading').hide();
jQuery('#publish').removeClass('button-primary-disabled');
return true;
}else{
alert("Please set a Featured Image!");
jQuery('#ajax-loading').hide();
jQuery('#publish').addClass('button-primary-disabled');
return false;
}
return false;
});
}
That doesn't work - the function doesn't get called even if #top is checked. Can anyone explain why? I'm used to PHP, and JavaScript often throws curveballs at me.
What does firebug or Chrome console tell you? You could try something like this:
$('#top').is(':checked')
as in (thanks RET):
jQuery('#post').submit(function() {
if ($('#top').is(':checked')) {
if (jQuery("#set-post-thumbnail").find('img').size() > 0) {
jQuery('#ajax-loading').hide();
jQuery('#publish').removeClass('button-primary-disabled');
return true;
}else{
alert("Please set a Featured Image!");
jQuery('#ajax-loading').hide();
jQuery('#publish').addClass('button-primary-disabled');
return false;
}
}
return false;
});
try
$('#top').is(':checked')
but the function submit only binds the function and calls it every time submit is clicked.
so you must put the checked check in the submit function
jQuery('#post').submit(function() {
if(!$('top').is(':checked')){ return };
if (jQuery("#set-post-thumbnail").find('img').size() > 0) {
jQuery('#ajax-loading').hide();
jQuery('#publish').removeClass('button-primary-disabled');
return true;
}
alert("Please set a Featured Image!");
jQuery('#ajax-loading').hide();
jQuery('#publish').addClass('button-primary-disabled');
return false;
});
Yeah, that logic won't quite do what you're hoping for. Try something like:
jQuery('#post').submit(function() {
if ($('#top').is(':checked')) {
// all your existing code
I could be wrong, but I don't think the answer given by #greener is going to work, because that will only declare the submit function if #top is checked at page create time.
Related
I have tried to write js for my html form. js is working fine with the logically. But if logic fails,I mean if any condition fails it reloads the page,which I don't want. I am providing the code. Please point me out the mistake in js if any.
window.onload = function() {
document.getElementById('submitlink').onclick = function() {
var bflag = document.addpro.brandflag;
var brand = document.addpro.brand1.value;
var cflag = document.addpro.catflag;
var cat = document.addpro.cat1.value;
var color1 = document.addpro.color1.value;
var color2 = document.addpro.color2.value;
if(cb_validation(bflag,brand))
{
if(cb_validation(cflag,cat))
{
if(colorcheck(color1,color2))
{
document.getElementById('addproform1').submit();
return false;
}
}
}
}
function cb_validation(flag,field)
{
if(flag[0].checked)
{
if(field==0)
{
alert('Please Select Both Brand And Category');
field.focus();
return false;
}
else
return true;
}
else
return true;
}
function colorcheck(c1,c2)
{
if((c1==0) && (c2==0))
{
alert('Please Select Both Colours');
document.addpro.color1.focus();
return false;
}
else if((c1==0))
{
alert('Please Select 1st Colour');
document.addpro.color1.focus();
return false;
}
else if((c2==0))
{
alert('Please Select 2nd Colour');
document.addpro.color2.focus();
return false;
}
else
return true;
}
}
I am rookie in js. Please also tell me if I have done any mistake.
return false is what keeps the page from reloading. Right now it is inside your final color check condition. If you never want the page to reload it needs to be after your first cb_validation condition.
Submit() is causing the page refresh which is in below line
document.getElementById('addproform1').submit();
Also both your function is returning true becauseyou are returning true in else block. Hope this points you to right direction....
Good luck....
I have a form with 5 fields all with the class 'required'
Im trying to ensure that on submit these fields arent empty, if they are, add a class, if not, return true - ive tried the following only with no luck, even if the fields are empty the form still submits.
$('.submit').click(function(){
if($('.required').val() == "") {
$('.required').addClass('error');
return false;
} else {
return true;
};
});
Try:
$('.submit').click(function(e){
if(!$('.required').val()) {
$('.required').addClass('error');
e.preventDefault();
} else {
return true;
};
});
Try this:
$('.submit').click(function() {
$('.required').removeClass('error').filter(function() {
return !$.trim(this.value).length;
}).addClass('error');
});
Class error is added to empty fields only and is removed otherwise.
http://jsfiddle.net/dfsq/2HxaF/
Another variation which can be useful for your task: additional validation on fields blur:
$('.submit').click(validate);
$(document).on('blur', '.required', function() {
validate($(this));
});
function validate($field) {
($field instanceof jQuery && $field || $('.required')).removeClass('error').filter(function() {
return !$.trim(this.value).length;
}).addClass('error');
}
http://jsfiddle.net/dfsq/2HxaF/1/
if($('.required') will return a collection of jQuery objects, while the call to .val() will only use the first element of that collection to perform your test.
try something like this (EDIT: don't need to do a loop or test, since filter expr will take care of that for you):
$('.submit').click(function(e) {
var ins = $('input.required[value=""]');
ins.addClass('error');
return false;
}
return true;
}
You should use filter to get the empty fields. The form submit is also better to use so that it will handle enter key presses too. If not then you will have to handle the enter key presses inside the form that will trigger the submit event of the form
$('yourform').submit(function(){
// empty will contain all elements that have empty value
var empty = $('.required').filter(function(){
return $.trim(this.value).length === 0;
});
if(empty.length){
empty.addClass('error');
return false;
}
});
A little late to the party but I think this is the best solution:
Replace ALL required fields that weren't filled:
http://jsfiddle.net/LREAh/
$('form').submit(function(){
if(!$('.required').val()) {
$('.required').attr('placeholder', 'You forgot this one');
return false;
} else {
return true;
};
});
Replace only the required field of the submitted form: http://jsfiddle.net/MGf9g/
$('form').submit(function(){
if(!$(this).find('.required').val()) {
$(this).find('.required').attr('placeholder', 'You forgot this one');
return false;
} else {
return true;
}
});
Of course you can change attr('placeholder', 'You forgot this one'); for addClass('error'); -- it was only for demonstration. You don't need the id="formX" on the html btw, I was just trying something else out and forgot to remove.
Im having problem altering jQuerys beforeunload() functionality, depending on user actions.
$(document).ready(function() {
$(window).bind('beforeunload', function() {
if (billChanged == false) {
return false;
}
else if ( savebutton was clicked ) {
return false;
}
else {
return "refreshing page without saving, huh? you're a bad boy!";
}
});
});
The issue im having, that i can't come up with a way to check if 'savebutton' was clicked, as typed in else if clause in the snippet above.
The form itself is quite complicated, and i'm not able to alter it that much.
$(document).ready(function() {
var not_saved = true;
$('#saveButtonId').on('click', function() {
not_saved = false;
})
$(window).on('beforeunload', function() {
if (not_saved && billChanged)
return "refreshing page without saving, huh? you're a bad boy!";
}
});
});
you can define a global variable. Change it's value onclick of the button, and then check it in your function
var clickedButton = false;
Then your html
<input type="button" .... onclick="clickedButton=true;">
and then in your function
else if ( clickedButton ) {
return false;
}
I have this
$("#formNewsletter").submit(function(){
return false;
})
It works as expected - the form is not submited.
When i write this, it seems like it is returning true (the form is being send)
$("#formNewsletter").submit(function(){
if($("#newsletterSelSpec div").length() > 0)
{
alert("Good");
}
else
{
alert("Please add at least one speciality!");
}
return false;
})
I would like to understand why is this happening and how can I make it work.
Thank you!
the property length isn't a method.
Use $("#newsletterSelSpec div").length > 0.
You can prevent the default behavior of an event using preventDefault() witch is a method in the first argument. (event).
$("#formNewsletter").submit(function(event) {
event.preventDefault();
if($("#newsletterSelSpec div").length() > 0)
{
alert("Good");
}
else
{
alert("Please add at least one speciality!");
}
});
Not sure, but the problem can be that the alert stops the process of the script and not the submit event.
$("#formNewsletter").submit(function(e) {
if ($("#newsletterSelSpec div").length > 0) {
alert("Good");
} else {
e.preventDefault(); // prevent the form submission
alert("Please add at least one speciality!");
}
});
NOTE
you're using .length(), but it should be .length only, that means
$("#newsletterSelSpec div").length
hi i check the blank field in the form and alert the user. but when alert the user it posts the data i couldnt return false not to refresh the page
$('#loginAccount').submit(function() {
$(this).find(':input:text').each(function(i) {
if($(this).val()=="") {
// alert($('label').eq(i).html())
$('#alert3').html('Please fill all fields.');
return false;
}
});
});
$('#loginAccount').submit(function() {
var valid = true;
$(this).find(':input:text').each(function(i) {
if($(this).val() == "") {
// alert($('label').eq(i).html())
$('#alert3').html('Please fill all fields.');
valid = false;
}
});
return valid;
});
You are currently returning from the each. What you need to do is track whether it's valid and then use that value as the return from your submit.
return false; takes on a different meaning inside of a jQuery each(). It is used to break out of the each. Maybe you could set a flag that is observed after the each() to see if the validation succeeded.
You need to return false in the submit function, not the each function:
$('#loginAccount').submit(function() {
var isValid = true;
$(this).find(':input:text').each(function(i) {
if($(this).val()=="")
{
isValid = false;
//alert($('label').eq(i).html())
$('#alert3').html('Please fill all fields.');
}
});
return isValid;
});
May be you shoul use closure to return a value?
$('#loginAccount').submit(function() {
var result = true;
$(this).find(':input:text')
.each(function(i) {
if($(this).val()=="")
{
//alert($('label').eq(i).html())
$('#alert3').html('Please fill all fields.');
result = false;
}
});
return result;
})