I have a (very) basic validation script. I basically want to check for any inputs with class .required to see if there values are a) blank or b) 0 and if so, return false on my form submit. This code does not seem to return false:
function myValidation(){
if($(".required").val() == "" || $(".required").val() == 0){
$(this).css({ backgroundColor:'orange' }) ;
return false;
}
}
Appending this function to my onSubmit handler of my form is not returning any results. Any light shed on this matter will be appreciated.
I am basically after a function that iterates through all the inputs with class .required, and if ANY have blank or 0 values, return false on my submit and change the background colour of all badly behaved inputs to orange.
Your code currently gets the .val() for the first .required, from the .val() documentation:
Get the current value of the first element in the set of matched elements.
You need to filter through each one individually instead, like this:
function myValidation(){
var allGood = true;
$(".required").each(function() {
var val = $(this).val();
if(val == "" || val == 0) {
$(this).css({ backgroundColor:'orange' });
allGood = false;
}
});
return allGood;
}
Or a bit more compact version:
function myValidation(){
return $(".required").filter(function() {
var val = $(this).val();
return val == "" || val == 0;
}).css({ backgroundColor:'orange' }).length === 0;
}
Try this jQuery selector:
$('.required[value=""], .required[value=0]')
You could also do it by defining your own custom jQuery selector:
$(document).ready(function(){
$.extend($.expr[':'],{
textboxEmpty: function(el){
return ($(el).val() === "");
}
});
});
And then access them like this:
alert($('input.required:textboxEmpty').length); //alerts the number of input boxes in your selection
So you could put a .each on them:
$('input.required:textboxEmpty').each(function(){
//do stuff
});
Related
I have this code that validates if ContentPlaceHolder1_locationTextBox has text in it before newIndex can become 3.
if ((newIndex === 3 && $("#ContentPlaceHolder1_locationTextBox").val() == "")) {
$('#ContentPlaceHolder1_locationLabelV').show();
return false;
}
else {
$('#ContentPlaceHolder1_locationLabelV').hide();
}
However I also have ContentPlaceHolder1_countryTextBox & ContentPlaceHolder1_seaTextBox on the page with thier respective labels, how can I modify the script so that it validates against all textboxes?
I tried adding a horrible or statement however this was causing the page to freeze. What s the best method to check against all three textboxes?
You can add class for all inputs, example: validate
After you can create JS function. You can fire this function as you wish.
function check(){
$('.validate').each(function(){
label = $("label[for='"+$(this).attr('id')+"']");
if ((newIndex === 3 && $(this).val() == "")) {
label.show();
return false;
}
else {
label.hide();
}
});
}
function validate(value) {
if ...
//show div
else ...
// hide div
}
$("input[type='text']").each(function(){
//value from input text field
var myval = $(this).val();
//call validation function
validate(myval);
});
I'm writing a small required HTML5 attribute fallback for various inputs. It's going pretty well so far, but I'm having trouble when checking a radio button is ':checked' and using the 'OR' || operator in the loop:
if (self.val() === '' || self.is(':not(:checked)')) {
For some reason when I add this it breaks the script slightly and will indicate that the input fields (type=text) are empty when they're not. Is there a better way at all to loop through and indicate the difference between an input type 'text' and 'radio'?
Here's the loop:
var reqClass = $('.required')
reqClass.each(function(){
var self = $(this)
// if empty
if (self.val() === '' || self.is(':not(:checked)')) {
// if it doesn't have require-checked class
if (!self.hasClass('require-checked')) {
self.addClass('require-checked')
self.parent().append('<span class="form-error">This field is required.</span>')
}
e.preventDefault()
//$('.form-submit').attr('disabled', true)
// if it's been checked, but there is a value now
} else if (self.hasClass('require-checked') && !(self.val() === '')) {
self.siblings('.form-error').hide()
}
})
Classes are obviously present for 'fallback' browsers and changed on the fly. Here's a JSFiddle, thank you for any help:
http://jsfiddle.net/cyncV/2/
A text box is indeed :not(:checked) (even if it has text in it), so the text boxes are showing as empty when they are not.
Perhaps something like
if (self.val() === '' || self.is(':checkbox:not(:checked)') || self.is(':radio:not(:checked)')
var self = this;
var empty = self.type=='checkbox' ? !self.checked : self.value=='';
if (empty) {
// do stuff
}
FIDDLE
There is a solution :
var checked = (self.is(':checkbox') || self.is(':radio')) ? self.is(':not(:checked)') : false;
if (self.val() === '' || checked) {}
Just add a little condition that if input is checkbox or radio, it look if it's checked, else it return false. Then pass the result into the if condition.
The following is some code for making sure people can't submit if the value of an input with the attribute data-fill="fill" is equal to ''. My problem is that it checks the IF statement from first to last input. This means that if the first input has a value, the form will submit; if the first two inputs are filled, it will submit and so forth... If the first input isn't filled, it works fine for the other inputs. Is it possible to ensure that it checks all inputs before returning true or false?
$('form').submit(function() {
var input = $('input, textarea');
if (input.data('fill') == 'fill' && input.val() == '') {
return false;
}
});
I know I can solve this problem by targeting each input individually with "else if", but that just seems like the wrong way to do it.
To consider all of the input values use the each method.
$('form').submit(function() {
var allFilled = true;
$('input, textarea').each(function () {
if ($(this).data('fill') === 'fill' && $(this).val() === '') {
allFilled = false;
}
});
return allFilled;
});
I have a form with several <select> elements on it.
I'd like to check that the value of all select elements is '0'. How can I do this elegantly?
Currently I have this:
var all_zero = true;
$('myform select').each(function() {
if ($(this).val() !== '0') {
all_zero = false;
}
});
if (all_zero) { //do something
Does anyone know a nicer way to do it?
Test for the value in the selector.
var non_zero = $('myform select[value!="0"]').length;
if (non_zero === 0) { //do something
So if there's no select that does not have the value "0", non_zero === 0 will be true.
That is the correct way to do it, one way for getting it cleaner is only declaring a variable when necessary. like so:
$('myform select').each(function() {
if ($(this).val() !== '0') {
some_zero = true;
}
});
if (!some_zero) { //do something
Your code is nice and you can try :
var all_zero = $('myform select').filter(function(){return $(this).val()!='0'}).length>0
I have HTML construction like this
<div class="qn-block">
<input type="text" class="quantity-number" name="quantity-number" value="2" />
Refresh
</div>
For inputs with value > 1 i have to disable ".refresh-q". For inputs with value = 1 disable ".refresh-q" and ".remove".
How can I achieve this?
In order to disable an anchor you could define a click handler which returns false:
function disableAnchor() {
return false;
}
But you could also hide it or whatever.
and then:
$('.quantity-number').each(function() {
var value = parseInt($(this).val(), 10);
if (isNaN(value)) {
return;
}
if (value > 1) {
$(this).siblings('.refresh-q').addClass('disabled').click(disableAnchor);
} else if (value === 1) {
$(this).siblings('.refresh-q, .remove').addClass('disabled').click(disableAnchor);
}
});
Try this. You cannot disable a link, so I have simply hidden them. There are alternatives to simply hiding the element, such as removing the A element completely, or returning false when clicked, if you'd prefer to use those instead.
$(".quantity-number").change(function() {
var val = $(this).val()
if (val = 1) {
$(this).siblings(".refresh-q, .remove").hide();
}
else if (val > 1) {
$(this).siblings(".refresh-q").hide();
}
});