Bird87 ZA
Bird87 ZA

Reputation: 2160

Radio Button, Text Area and Input check

I have a form with all the input fields as class item. When I click submit, it checks, with the following function if all values are filled in.

$.each($(".items"),function(i,e){
    // loop through all the items
    if(e.value == "" || !$("input[name='"+e.name+"']:radio:checked").length)
        if(error.indexOf(e.title) === -1)
            error += e.title + "<br/>";
    });

This form comprises of text areas, radio boxes and normal text input fields. It returns all the radio boxes not filled in, as well as all the text inputs not filled in. But then it also returns ALL the text areas, regardless of whether it's filled in or not.

I first thought it was because I specified it to check the value, but it seems the value check does in fact check text areas, so it can't be that.

Could anyone assist me in making it return only empty elements?

Upvotes: 1

Views: 459

Answers (3)

Bird87 ZA
Bird87 ZA

Reputation: 2160

So I used a combination of JBRTRND and Florian Margaine's answers as neither wanted to work 100% correctly.

I just put this here incase someone is stuck on the same issue. I in no way take credit for ANY of the help I received from them and I'm really thankful for it.

This is how I fixed it:

$.each($(".items"),function(){
    // loop through all the items
        // and alert the value
        if ( this.type == 'radio' && !$("input[name='"+this.name+"']:radio:checked").length) {
            if(error.indexOf(this.title) === -1)
                error += this.title + "<br/>";
        }
        else if ( this.value === '' ) {
            if(error.indexOf(this.title) === -1)
                error += this.title + "<br/>";
        }
    });

Upvotes: 0

Florian Margaine
Florian Margaine

Reputation: 60717

$.each( $( '.items' ), function() {
    if ( ( this.type === 'checkbox' || this.type === 'radio' ) && !this.checked ) {
        // Go
    }
    else if ( this.value === '' ) {
        // Do your stuff
    }
});

Unfortunately, it seems there is no other choice but to separate the cases.

Upvotes: 3

jbrtrnd
jbrtrnd

Reputation: 3833

$.each($('.items'),function(i,elem){
    if( ($(elem).attr('type') == 'radio' || $(elem).attr('type') == 'checkbox') && !$(elem).is(':checked') ) {
               // RADIOS AND CHECKBOXES EMPTY
    } else if( $(elem).val().length == 0 ) {
              // INPUTS TYPE TEXT AND TEXTAREA EMPTY
    }
});

Upvotes: 2

Related Questions