check all input values of same class is empty jquery - javascript

Here I have many input text fields with same class like
<input type="text" class="MyClass"></input>
<input type="text" class="MyClass"></input>
<input type="text" class="MyClass"></input>
My requirement is to check wheather all input fields of this class is empty or not.
I've tried this
if(!('.MyClass').val()){
alert("empty");
}
But it doesn't make any result. Can anyone help?

You can check
$('button').click(function() {
var $nonempty = $('.MyClass').filter(function() {
return this.value != ''
});
if ($nonempty.length == 0) {
alert('empty')
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="MyClass" />
<input type="text" class="MyClass" />
<input type="text" class="MyClass" />
<button>test</button>
Or using a flag
$('button').click(function() {
var flag = false;
$('.MyClass').filter(function() {
if (this.value != '') {
flag = true;
//no need to iterate further
return false;
}
});
if (!flag) {
alert('empty')
}
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="text" class="MyClass" />
<input type="text" class="MyClass" />
<input type="text" class="MyClass" />
<button>test</button>

You can compare the length of number of input with number of empty input using :
var allemptylength=$(".MyClass").filter(function() {
return this.value.length !== 0;
})});
if($('.MyClass').length== allemptylength.length){
alert("all empty");
}
Working Demo

To make sure each classes are checked, use
$.each($('.MyClass'),function() {
if ($(this).val().length == 0) {
alert('empty');
}
});

You can check it like this:
var isEmpty = !$('.MyClass').filter(function() {
return this.value.trim();
}).length;
Also remove all </input> tags. input elements are self-closable.

try this
var hasNoValue;
$('.MyClass').each(function(i) {
if ($(this).val() == '') {
hasNoValue = true;
}
});
if (hasNoValue) {
alert('All have no value');
}

try is(':checked')
$('.MyClass').each(function(){
alert($(this).is(':checked');)
});
this will alert only the checked elements.

$('input').each(function(index,value){
if($(this).val()!=''){
$(this).addClass('success');
}else{
$(this).removeClass('someClass');
$(this).addClass('warning');
$(this).css('border', '1px solid red');
//do something else...
}
});

Try this . 100% working..
var emptyLength = $(".MyClass").filter(function() {
return this.value == "";
}).length;
if (emptyLength > 0)
{
alert("Please enter all peramerter's value");
return;
}
Thanks.

Try this. It works for me
var flag = 1;
$(".MyClass").each(function(i){
if ($(this).val() == "")
flag++;
});
if (flag == 1)
alert('all have values');
else
alert('some or all doesn\'t have value');

Related

how to check hidden input is empty or not use else if conditions in laravel

this is my hidden input field
<input type="hidden" id="hdnship" name="origin_port" value="">
this is my function to get value hidden input field
function myfunction(){
$('#printarray').on('click', function() {
var array = [];
$("input:checkbox[name=origin_port]:checked").each(function() {
array.push($(this).val());
});
alert(array);
$('#hdnship').val(array);
});
}
You can check you input if it is not empty this way:
if( !$("input").val() ) {
console.log("Empty");
}
or
if( $("input").val().length === 0 ) {
console.log("Empty");
}
or If you're sure it will always operate on a textfield element then you can just use 'this.value':
if( !$("input").value ) {
console.log("Empty");
}
I think you should be checking each input type text instead of checked attribute of a checkbox which is basically not the type of your hidden input:
function myfunction(){
$('#printarray').on('click', function() {
var array = [];
$("input[type=text]").each(function() {
if($(this).val().length !== 0) {
array.push($(this).val());
}
});
alert(array);
$('#hdnship').val(array);
});
}
You can try this also for check hidden empty or not
$(document).ready(function(){
$(".jsButton").click(function(){
var array = [],emptyvalue=[];
$("input[type=hidden]").each(function()
{
if($(this).val().length !== 0)
{
array.push($(this).val());
}
else
{
emptyvalue.push("value");
}
});
$('#lblHasValue').html(array.join(','));
$('#lblNotValue').html(emptyvalue.join(','));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="hidden" value="hidden1">
<input type="hidden" value="hidden2">
<input type="hidden" value="hidden3">
<input type="hidden">
<input type="hidden">
<button type="button" class="jsButton">Set & Get Hidden Value</button> <br/>
<lable id="lblHasValue"></lable> <br/>
<lable id="lblNotValue"></lable>
You can set if hidden field has no value if hidden field has value
you get and set

How to return name values of empty fields in jQuery

I have this piece of code that validates an html form and highlight empty fields with red borders.
What I want is to be able to return the name values of empty input fields so I can output them.
var isValid = $('input, textarea').not('input:disabled').filter(function() {
return !this.value;
}).css('border-color', 'red').length == 0;
if(isValid){
console.log('Ok');
}else if(!isValid){
console.log($(this).attr('name') + 'must not be empty');
}
When there are no empty fields the first part works well, but when there are empty fields I was expecting to get the name values of those inputs in the console. But I keep getting undefined
Can use map()
var isValid = $('input, textarea').not('input:disabled').filter(function() {
return !this.value;
}).css('border-color', 'red')
var names = isvalid.map(function(){
return this.name;
}).get()
The reason is that isValid is boolean (.length == 0). You need to get the filtered elements like this:
var isValidEl = $('input, textarea').not('input:disabled').filter(function() {
return this.value.length == 0;
}).css('border-color', 'red');
And then, change the condition to:
if(!isValidEl.length){
console.log('Ok');
} else {
isValidEl.each(function() {
console.log($(this).attr('name') + ' must not be empty');
});
}
Exmaple:
var isValidEl = $('input, textarea').not('input:disabled').filter(function() {
return this.value.length == 0;
}).css('border-color', 'red');
if(!isValidEl.length){
console.log('Ok');
} else {
isValidEl.each(function() {
console.log($(this).attr('name') + ' must not be empty');
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="" name="emptyInput">
<textarea name="emptyTextaria"></textarea>
<textarea name="nonEmptyTextaria">HELLO</textarea>
<input type="text" value="HELLO" name="nonemptyInput">

can we use and operator to combine multiple jQuery events

I want to use jQuery to see if three text boxes are changed so I can send data through AJAX.
I tried a simple script:
$("#name, #position, #salary").change(function()
{
console.log("All data are changed");
});
Where name, position and salary are the respective IDs of three text box.
The result was that when I change the first one:
And when I changed the second:
And here is the third one:
So, I've got the message when separately each text box is changed. What I do need is when the three are changed, display the message. I am new to jQuery, so I want to know if I can use something like IF ... AND ... AND in jQuery.
A lot of validation frameworks have the concept of a dirty input once a user has changed the value. You could implement this and check when all your fields are dirty.
$("#name, #position, #salary").change(function() {
this.classList.add("dirty");
if ($(".dirty").length === 3) {
console.log("All data are changed");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="name" />
<input id="position" />
<input id="salary" />
We can abstract this out into a jQuery plugin for re-usability
$.fn.allChange = function(callback) {
var $elements = this;
$elements.change(function() {
this.classList.add("dirty");
if (callback && $elements.filter(".dirty").length === $elements.length) {
callback.call($elements);
}
});
return $elements;
}
$("#name, #position, #salary").allChange(function() {
console.log("All data are changed");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="name" />
<input id="position" />
<input id="salary" />
You can store changed inputs in an array, and check it's length to detect if all of them where changed.
var changedInputs = [];
$("#name, #position, #salary").change(function()
{
changedInputs.push(this.id);
if(changedInputs.length === 3) {
alert('All 3 inputs where changed!');
}
});
You can try:
var changedInputs = [];
$("#name, #position, #salary").change(function()
{
if !(changedInputs.include(this.id) ){
changedInputs.push(this.id);
if(changedInputs.length == 3) {
alert('All 3 inputs where changed!');
}
});
You can also use this approach. Fiddle
var isNameChanged, isPositionChanged, isSalaryChanged = false;
function fieldsChanged()
{
var id = $(this).attr('id');
if (id == 'name') isNameChanged = true;
else if (id == 'position') isPositionChanged = true;
else if (id == 'salary') isSalaryChanged = true;
if (isNameChanged && isPositionChanged && isSalaryChanged) {
console.log('All have been changed');
isNameChanged = isPositionChanged = isSalaryChanged = false;
}
}
$(function(){
$('#name, #position, #salary').change(fieldsChanged);
});
Try using a class:
<input class="need">
<input class="need">
<input class="need">
$(".need").change(function()
{
var all = 0;
$(".need").each(function(i,v){
if ($(v).val().length >0 ) {
all+=1;
}
});
if(all.length == 3) {
alert('All 3 inputs where changed!');
}
});
Store the multiple selectors in a variable. On .change() loop through the elements in the multiple selector to test the input values. If all inputs have content an additional function can be called.
$(document).ready(function(){
var $selectors = $('#input1, #input2, #input3');
$selectors.change(function(){
var allChanged = true;
console.log($(this).attr('id') + ' was changed.');
$selectors.each(function(){
if ($(this).val() == '') {
allChanged = false;
}
});
if (allChanged) {
// $().ajax();
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input1">
<input id="input2">
<input id="input3">
one possible solution:
var needed = ["name", "position", "salary"];
$("#name, #position, #salary").change(function()
{
if(needed.length == 0) return;
needed.splice(needed.indexOf($(this).attr('id')), 1);
if(needed.length == 0)
console.log("All data are changed");
});
first, you need to init the array "needed" to all required fields
then, when a field is changed, you remove that field from the needed array
once the array is empty, all required values are changed ;)
the first condition is to ensure not to log the message more than once
You can compare current input value to default one, then the logic could be like following:
btw, i set a common class for all inputs to check, because this is how it should be done imho...
$('.inputToCheck').on('change', function() {
var allInputsChanged = !$('.inputToCheck').filter(function() {
return this.value === this.defaultValue;
}).length;
if (allInputsChanged) alert('All inputs changed!');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="name" class="inputToCheck">
<input id="position" class="inputToCheck">
<input id="salary" class="inputToCheck">

Jquery on keypress

I'm looking for a function that gives an alert when a certain character key (g) is pressed in the first position of a postal code, and then disables the submit button if the postal code has a letter G in the beginning.
Is this possible?
My current code to detect a key up on the postal code field at the moment is this:
$(document).ready(function() {
var someTextInputField = "#postal-code";
$(someTextInputField).on("keyup", function() {
alert('not a valid postal code');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="postal-code" />
Javascript without extra libraries
document.addEventListener("input", function(e) {
if (e.target.id === "postal-code") {
var disable = /^g/i.test(e.target.value),
submit = document.getElementById("submit");
if (disable && !submit.disabled) {
alert("You cannot start a postal code with a G");
}
submit.disabled = disable;
}
});
<input placeholder="Address" />
<input id="postal-code" placeholder="Postal Code" />
<button id="submit">Submit</button>
jQuery
$(document).on("input", "#postal-code", function (e) {
var disable = /^g/i.test(this.value),
$submit = $("#submit");
if (disable && !$submit.prop("disabled")) {
alert("You cannot start a postal code with a G");
}
$submit.prop("disabled", disable);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input placeholder="Address" />
<input id="postal-code" placeholder="Postal Code" />
<button id="submit">Submit</button>
Check this fiddle http://jsfiddle.net/oyc2L9sy/12/
html:
<input id="test" type="text" />
javascript:
$(document).ready(function() {
$("#test").on("keypress", function(e) {
if ((e.keyCode == '65') ||
(e.keyCode == '71')) {
alert('not a valid postal code');
return false;
}
});
});
You can use this.value[0] to get the first character of the input. Then test whether it's one of the allowed characters.
$("#input").on("keyup", function() {
if (this.value != '') {
var firstchar = this.value[0].toUpperCase();
if (firstchar != 'A' && firstchar != 'G') {
alert('not a valid postal code');
$("#submitID").prop("disabled", true);
} else {
$("#submitID").prop("disabled", false);
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="input"/>

Required field validation jquery showing error message

I validated some fields in my form.. But i have some issues..If without enter fields it shows error message.. If fill out the field still error message is showing..
How to put that ?
My code
$("#Name").focus();
$("#Name").blur(function(){
var name=$('#Name').val();
if(name.length == 0){
$('#Name').after('<div class="red">Name is Required</div>');
}
else {
return true;
}
});
$("#Address").blur(function(){
var address=$('#Address').val();
if(address.length == 0){
$('#Address').after('<div class="red">Address is Required</div>');
return false;
}
else {
return true;
}
});
can anyone help me please?????
You should remove this labels after that user input some data
$("#Name").focus();
$("#Name").blur(function(){
var name=$('#Name').val();
if(name.length == 0){
$('#Name').after('<div class="red">Name is Required</div>');
}
else {
$('#Name').next(".red").remove(); // *** this line have been added ***
return true;
}
});
$("#Address").blur(function(){
var address=$('#Address').val();
if(address.length == 0){
$('#Address').after('<div class="red">Address is Required</div>');
return false;
}
else {
$('#Address').next(".red").remove(); // *** this line have been added ***
return true;
}
});
jsfiddle: DEMO
Your code has bug that it places div as many as time as you blur in empty textbox.
This bug is also removed by my code See-:
Working Demo http://jsfiddle.net/XqXNT/
$(document).ready(function () {
$("#Name").focus();
$("#Name").blur(function () {
var name = $('#Name').val();
if (name.length == 0) {
$('#Name').next('div.red').remove();
$('#Name').after('<div class="red">Name is Required</div>');
} else {
$(this).next('div.red').remove();
return true;
}
});
$("#Address").blur(function () {
var address = $('#Address').val();
if (address.length == 0) {
$('#Address').next('div.red').remove();
$('#Address').after('<div class="red">Address is Required</div>');
return false;
} else {
$('#Address').next('div.red').remove();
return true;
}
});
});
It's better if you use required attribute which does the same work with less code and better manner.
HTML5
<input type="text" name="name" required />
<input type="text" name="address" required />
Try this code (I just changed the structure and added return false) :
$("#Name").focus()
$("#Name, #Address").blur(function(){
if($(this).val().length == 0){
$(this).after('<div class="red">This field is required</div>');
} else {
$(this).next('.red').remove()
}
});
But I think the best way is to add the required attribute to your fields like this :
<input type="text" name="name" required />
<input type="text" name="address" required />
Try to remove the added html in else condition.
if(name.length == 0){
$('#Name').after('<div class="red">Name is Required</div>');
}
else {
$('.red').empty(); //here
return true;
}
And the same for $("#Address")

Categories