ultrasamad
ultrasamad

Reputation: 368

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

Upvotes: 2

Views: 77

Answers (2)

charlietfl
charlietfl

Reputation: 171669

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()

Upvotes: 2

Alon Eitan
Alon Eitan

Reputation: 12025

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">

Upvotes: 2

Related Questions