check if all text inputs are empty - javascript

I want to check if all text inputs with class 'textinput' are empty, but it only seems to check if the first input is empty or not, I can't figure out why. can anyone see what I'm doing wrong?
$('#check').click(function(){
var allEmpty;
$('.textinput').each(function(){
if(!$('.textinput').val()){
allEmpty = true;
}
});
if (allEmpty == true){
alert('all empty');
}
});

Find all .textinput that are not empty, and check the selector length. If none exist, they are all empty :
$('#check').on('click', function(){
var allEmpty = ! $('.textinput').filter(function() {
return $.trim( this.value ) != "";
}).length;
if (allEmpty) alert('all empty');
});
or
if ( ! $('.textinput[value !=""]').length ) alert('all empty');

Try checking against the opposite logic. If any of the values are set, then they're not all empty.
Also, you want to make use of $(this) when you're within the context of the .each() function. Otherwise, calling $('.textinput') will re-select those elements again rather than working on the current one.
Adding $.trim() ensures that whitespace is not counted as an actual value, but you can remove this if you want to count whitespace as a value.
$('#check').click(function() {
var allEmpty = true;
$('.textinput').each(function(){
if ($.trim($(this).val())) {
allEmpty = false;
}
});
if (allEmpty == true){
alert('all empty');
}
});

Your condition is wrong; you are setting allEmpty = true for each single item.
You have to invert your logic:
$('#check').click(function(){
var almostOneNotEmpty = false;
$('.textinput').each(function(){
if($(this).val()){
almostOneNotEmpty = true;
}
});
if (!almostOneNotEmpty == true){
alert('all empty');
}
});

this should be your condition >>
if(!$('.textinput').val()){
}else {
allEmpty = true;
}

This simple check will tell you if they are all empty:
var isEmpty = !$('.textinput').map(function() { return this.value; }).get().join('');
This will give you boolean true if all the fields are blank.

You need to use the element that is selected by the each method by using "this".
$('#check').click(function () {
var allEmpty;
$('.textinput').each(function () {
if (!$(this).val()) {
allEmpty = true;
}
});
if (allEmpty == true) {
alert('all empty');
}
});

Related

How come multiple classes not targeting in textarea?

I want to use validate_empty_field function for both classes .log and .log2. For some reason only .log is targeted but .log2 textarea is not. When you click on text area, if empty, both should show validation error if the other one is empty or if both empty.
$(document).ready(function() {
$('#field-warning-message').hide();
$('#dob-warning-message').hide();
var empty_field_error = false;
var dob_error = false;
// $('input[type=text], textarea')
$('.log, .log2').focusout(function () {
validate_empty_field();
});
function validate_empty_field() {
var field = $('.log, .log2, textarea').val();
// var first_name_regex = /^[a-zA-Z ]{3,15}$/;
if (field.length == '') {
$('#field-warning-message').show();
$('#field-warning-message').html("Please fill out form!");
empty_field_error = true;
} else if (field.length < 1) {
$('#field-warning-message').show();
$('#field-warning-message').html("Please fill out form!");
empty_field_error = true;
} else {
$('#field-warning-message').hide();
}
}
$('.verify-form').submit(function () {
empty_field_error = false;
dob_error = false;
validate_empty_field();
if ((empty_field_error == false) && (dob_error == false)) {
return true;
} else {
return false;
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea class="log"></textarea>
<textarea class="log2"></textarea>
<div id="field-warning-message"></div>
You should pass the event to the handler so you have access to the target
Change your event listener line to this:
$('.log1, .log2').focusout(validate_empty_field);
and then accept an argument in validate_empty_field
function validate_empty_field(ev){
var field = $(ev.target).val();
if(!field.length){
//textarea is empty!
}else{
//textarea is not empty!
}
}
in fact, you could do all of this in an anonymous function you have already created, and use the on method to stick with JQuery best practices:
$('.log1, .log2').on('focusout', function(){
if(!$(this).val().length){
//this textarea is empty
}else{
//this textarea is not empty!
}
});
And yes, adding one class to all textareas and swapping out .log1, .log2 for that class would be a better option.
EDIT: Final option should cover all requirements.
$('.log').on('focusout', function(){
$('.log').each(function(){
if(!$(this).val().length){
//this textarea is empty
}else{
//this textarea is not empty!
}
}
});

disable anchor link '<a>' if one of my six checkboxes are not checked

How can I disable a anchor link if one(1) of my six(6) checkbox is not check?
var first_option = $('#pid-1590083, #pid-1590090, #pid-1590091, #pid-1590092, #pid-1590093, #pid-1590094');
$("a").click(function(e) {
if($("first_option").prop("checked") === false) {
e.preventDefault(); return false;
} else {return true;};
});
Your current logic doesn't work as you're only looking at the checked property of the first element you select, not all of them.
To achieve what you require, you can use the :checked selector to get all the checked elements within the selectors you provide, then check the length property of the result to see if there aren't any. Try this:
var $first_option = $('#pid-1590083, #pid-1590090, #pid-1590091, #pid-1590092, #pid-1590093, #pid-1590094');
$("#tmp_button-99035").click(function(e) {
if ($first_option.filter(':checked').length === 0) {
e.preventDefault();
alert('Please Choose Collar Colour To Continue');
};
});
first_option.prop("checked") will always check for first element. What you have to do is loop over all elements to check
Like this
$("#tmp_button-99035").click(function(e) {
var isChecked = false;
for (var i = 0; i < first_option.length; i++) {
if (first_option.eq(i).prop("checked")) {
isChecked = true;
break;
}
}
if (!isChecked) {
alert('Please Choose Collar Colour To Continue');
e.preventDefault();
}
return isChecked;
});
Well, the js snippet of yours is only checking the first element. So, you have to track other checkboxes as well for correct result.
var first_option = $('#pid-1590083, #pid-1590090, #pid-1590091, #pid-1590092, #pid-1590093, #pid-1590094')
$(document).on('click', '#tmp_button-99035', function (e) {
if ($(first_option).filter(":checked").length == 0) {
e.preventDefault();
}
});

Check to make sure all fields are filled Jquery

I'm trying to make an easy validator in jquery for my input fields.
Currently i got the following:
function checkInputs(){
var isValid = true;
$('.input-required').each(function() {
if($(this).val() === ''){
isValid = false;
return false;
}
});
return isValid;
}
And then i got a button right that is this:
$('#confirm').click(function () {
alert(checkInputs());
});
But this always returns true even if the input is empty.
Also after this works am going to make to where if all inputs are filled in, a button will be enabled to click on.
edited it so it has a selector now, still getting always true.
Thanks in advance
Try use the filter attribute to get the inputs that has a required attribute.
$('input').filter('[required]')
Added code to check if inputs are filled and enable or disable button. Note if we use this, there aint much point of the $('#confirm').click(function()); function since this button will only be enabled when the inputs are filled.
function checkInputs() {
var isValid = true;
$('input').filter('[required]').each(function() {
if ($(this).val() === '') {
$('#confirm').prop('disabled', true)
isValid = false;
return false;
}
});
if(isValid) {$('#confirm').prop('disabled', false)}
return isValid;
}
$('#confirm').click(function() {
alert(checkInputs());
});
//Enable or disable button based on if inputs are filled or not
$('input').filter('[required]').on('keyup',function() {
checkInputs()
})
checkInputs()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<input required>
<input required>
<input required>
<button id="confirm">check</button>
</form>
Try to target the element in this way:
$('input[required]')
This should do the trick.
if it is 0 then all input filled otherwise it will return 0 mean any one or more are empty input.
function checkInputs(){
var flag = 0;
$('input').each(function() {
if($(this).val() == ''){
return flag = 1;
}
});
return flag;
}
$('#confirm').click(function () {
alert(checkInputs());
});
Your selector is looking for a tagName <input-required></input-required> that obviously doesn't exist.
Add a dot prefix for class
Can also use filter() to simplify
function checkInputs(){
return !$('.input-required').filter(function() {
return !this.value;
}).length;
}
NOTE: Will not work on radios or checkbox if those are part of the collection of elements with that class and you would need to add conditional for type if that is the case
You forgot to put class symbol in jQuery:
function checkInputs() {
var isValid = true;
$('.input-required').each(function() {
if($(this).val() === ''){
isValid = false;
return false;
}
});
return isValid;
}
Try this..

Check whether the required field is not empty

I want to check whether the required field is empty or not.
I used the code below.
$(":input").each(function() {
if($(this).data('label')=='required')
{
if($(this).val() === "")
alert("Empty Fields!!");
}
});
But it was alert more than one time.
JSFiddle:
http://jsfiddle.net/hbk2a5qo/3/
Why not directly use required attribute in HTML:
<input id="name"type="text" data-label="required" required/>
You need to use a flag
$(document).ready(function () {
$("#submit").click(function (e) {
e.preventDefault()
AlertSave();
});
});
function AlertSave() {
//use the flag to set the valid status in the loop
var valid = true;
//iterate over only the required elements
$(':input[data-label="required"]').each(function () {
if ($(this).val() === "") {
valid = false;
return false;
}
});
if (valid) {
//do your save
} else {
alert("Empty Fields!!");
}
}
Demo: Fiddle
As you have used $(":input").each() so it will go through all fields. But you can use flag to show alert only once.
function AlertSave() {
var alertShown=false;
$(":input").each(function() {
if($(this).data('label')=='required')
{
if($(this).val() === "" && !alertShown)
{
alertShown=true;
alert("Empty Fields!!");
}
}
});
}
You Updated Fiddle
By using required attribute (which is recommended), this will return all the required input fields that has no value:
var inputsWithMissingValues = $('input[required]').filter(function(i, input) {
return !input.value.length;
});
So, if the length of that is more than zero, then you have required fields with missing value.

Check if input value is empty and display an alert

How is it possible to display an alert with jQuery if I click the submit button and the value of the input field is empty?
<input type="text" id="myMessage" name="shoutbox_msg" size="16" class="field_nosize" maxlength="150">
<input id="submit" type="submit" name="submit_post" class="button_nosize" value="Senden" onclick="sendMessage(); clearInput();">
$('#submit').click(function(){
if($('#myMessage').val() == ''){
alert('Input can not be left blank');
}
});
Update
If you don't want whitespace also u can remove them using jQuery.trim()
Description: Remove the whitespace from the beginning and end of a string.
$('#submit').click(function(){
if($.trim($('#myMessage').val()) == ''){
alert('Input can not be left blank');
}
});
Better one is here.
$('#submit').click(function()
{
if( !$('#myMessage').val() ) {
alert('warning');
}
});
And you don't necessarily need .length or see if its >0 since an empty string evaluates to false anyway but if you'd like to for readability purposes:
$('#submit').on('click',function()
{
if( $('#myMessage').val().length === 0 ) {
alert('warning');
}
});
If you're sure it will always operate on a textfield element then you can just use this.value.
$('#submit').click(function()
{
if( !document.getElementById('myMessage').value ) {
alert('warning');
}
});
Also you should take note that $('input:text') grabs multiple elements, specify a context or use the this keyword if you just want a reference to a lone element ( provided theres one textfield in the context's descendants/children ).
Also you can try this, if you want to focus on same text after error.
If you wants to show this error message in a paragraph then you can use this one:
$(document).ready(function () {
$("#submit").click(function () {
if($('#selBooks').val() === '') {
$("#Paragraph_id").text("Please select a book and then proceed.").show();
$('#selBooks').focus();
return false;
}
});
});
Check empty input with removing space(if user enter space) from input using trim
$(document).ready(function(){
$('#button').click(function(){
if($.trim($('#fname').val()) == '')
{
$('#fname').css("border-color", "red");
alert("Empty");
}
});
});
You could create a function that checks every input in an input class like below
function validateForm() {
var anyFieldIsEmpty = jQuery(".myclass").filter(function () {
return $.trim(this.value).length === 0;
}).length > 0
if (anyFieldIsEmpty) {
alert("Fill all the necessary fields");
var empty = $(".myclass").filter(function () {
return $.trim(this.value).length === 0;
})
empty.css("border", "1px solid red");
return false;
} else {
return true;
}
}
What this does is it checks every input in 'myclass' and if empty it gives alert and colour the border of the input and user will recognize which input is not filled.
Use this instead because just trying to check if the value is not equal to an empty string won't help if there are multiple spaces.
('#submit').onclick = function(){
let count = 0;
let notEmpty = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
for(let i=0; i < $('#myMessage').value.length; i ++){
for(let j = 0; j < notEmpty.length ; j++){
if($('#myMessage').value[i]== notEmpty[j]){
count += 1;
}
}
}
if(count==0){
alert("You cannot leave this blank");
}
}

Categories

Resources