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.
Related
I have a few select menus that include blank options. When both are blank (usually on the first page load), I would like to show some hidden div.
This is what I have:
$('.variant_options select').each(function() {
if ($(this).attr('value') === '') {
// some code here to show hidden div
console.log("No options chosen");
}
});
This doesn't seem to work.
Edit 1
For what it's worth, I have tried something like this:
if (!$(this).attr('value'))
And that has seemed to work, but it breaks functionality elsewhere.
<select> elements don't have a value attribute, so you need to use .val() on the element to find out if the currently selected option is empty.
if ($(this).val() === '') {
// value of select box is empty
}
this.value === '' should also work
To check whether no options are selected:
if (this.selectedIndex == 0) {
// no option is selected
}
You can do so by using the following:
if($(this).val() === '') {
// value is empty
}
I believe also the following too:
if(!$(this).prop('value')) {
// It's empty
}
You can simply do this:
$('.variant_options select').each(function () {
if ($.trim($(this).val()) === '') {
// some code here...
}
});
jQuery can check for value by using $(this).val()
So you would do if ($(this).val === '')`
If you wanted to check for some other attribute, like href or src, you could do
if ($(this).attr('href') === ''
In case if you have spaces, use this trick:
if ($.trim($(this).val()) === '') { ...
I have a div which contain lots of input[type=text] fields. I want to put a check that user must have fill all the fields otherwise show error message. For this i tried :
if ($('div').children("input[type=text]").attr("value") == '')
flag = false;
else
flag = true;
But this will not check all the text field, it only checks the first-child . How can i check all the text field ?
Try to use find() instead
if ($('div').find("input[type=text]").val() == '')
To check over all input items you need to iterate over them using each().
Correct code would be:
$(function() {
$('input:submit').click(function(){
var flag = true;
$('div').find("input[type=text]").each(function(){
if($(this).val() === '') flag = false
});
alert(flag);
});
});
See demo on jsFiddle.
This code return true if all input[type=text] fields inside div are filled and false if at least one is empty.
The standard way
if(!$('div').find('#idOfTextField').val()){
//empty
}
if($("div").find('input:text[value=""]').length > 0)
{
alert("error");
return false;
}
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;
});
When using a WebKit browser (Chrome or Safari), if I try to get the default value of a checkbox, it returns "". However, the same javascript in Firefox or IE will return "on".
So lets say I have this checkbox on a page:
<input type="checkbox" id="chkDefaultValue">
I use this javascript to return all "input" elements on a page
var elems = document.getElementsByTagName('input');
Then I go through a loop that gets the value like this
elems[i].getAttribute('value')
When elems[i] is that checkbox, in Chrome or Safari it returns "", but Firefox or IE it returns "on".
Is there any way to use Javascript to return the "on" value in Safari or Chrome? In Chrome I use a jquery call that uses .val() and that actually returns "on", but I need a way to do this using Javascript in Safari.
Thanks!
EDIT:
I'm actually looking for the "value" attribute specifically since the "value" of a checkbox can be anything, like "cat" or "bike".
Use checked instead to see if a checkbox or radio input is selected.
If what you really want to do is get the value attribute, and not see if the checkbox is selected, then you need to set a value for the checkbox first. If nothing is set then you getting null is the normal behavior.
You can also replicate the Firefox and IE behavior by assigning on yourself as a default value:
var myVal = elems[i].getAttribute('value');
if(myVal === null)
myVal = 'on';
I think that it's because elems[i].getAttribute('value') is not what you should be using to get the state of a checkbox.
Try using elems[i].getAttribute('checked') or just elems[i].checked to get the state.
By the way, elems[i].getAttribute('value') can be shortened to just elems[i].value.
Just read your comment on another answer...
Here's the source for the .val() statement from the jQuery repo:
getVal = function(elem)
{
var type = elem.type, val = elem.value;
if (type === "radio" || type === "checkbox")
{
val = elem.checked;
} else if (type === "select-multiple") {
val = elem.selectedIndex > -1 ? jQuery.map( elem.options, function( elem ) {return elem.selected;}).join("-"):"";
} else if (elem.nodeName.toLowerCase() === "select") {
val = elem.selectedIndex;
}
return val;
}
That is pretty simple JavaScript, and you can just omit the .map() function.
Also, why not just test for the existence of the value property?
function niceValue(element)
{
if (element.value != '')
{
return element.value;
} elseif (element.checked) {
if (element.checked)
{
return 'on';
} else {
return 'off';
}
}
}
Good luck!
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
});