Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validation for dropdown boxes selection?

Here My requirement is once we select the SON or Father in one select box and if I select 'Mother-In-law' or 'Father-In_law' in another select boxes,I want one alert message like 'In-laws are not applicable'.

Here is my code,

if (arr.indexOf(!(($(this).val() == 'Son' || $(this).val() == 'Father'))) > -1) {
    alert('In-laws are not applicable');
    return false;
}

Can any one help me please. The jsFiddle is here.

-Thanks.

like image 462
Rajasekhar Avatar asked Jul 02 '13 15:07

Rajasekhar


2 Answers

You can check each one of the selects looking for Son or Father after the user selects Father-in-law or Mother-in-law:

if($(this).val()=='Mother-in-law' || $(this).val()=='Father-in-law'){

    //for each of the Relation selects, we check if anyone is Son or Father              
    $('.classSelect').each(function(){
        var currentSelect = $(this).val();
        if( currentSelect == 'Son' ||  currentSelect == 'Father'){
            alert("In-laws are not applicable");  
        }
    });

}   

Living example: http://jsfiddle.net/4QUMG/10/

Update

Living example using your arr array: http://jsfiddle.net/4QUMG/12/

Also, I would save the value of $(this).val() inside a variable.

like image 163
Alvaro Avatar answered Sep 29 '22 15:09

Alvaro


If I understand you, what you want is to see if "Son" or "Father" were already selected, and we're currently selecting an "in-law", to throw the error.

if (arr.indexOf('Son') > -1 || arr.indexOf('Father') > -1 && currentVal.indexOf('-in-law') > -1) {
        alert('In-laws are not applicable');
        return false;
    }

That code will do that. If you want it to work in reverse, (i.e., we can't select in-law before son or father, either) we'd need to add this:

if ((arr.indexOf('Father-in-law') > -1 || arr.indexOf('Mother-in-law') > -1) && (currentVal === 'Son' || currentVal === 'Father')) {
        alert('In-laws are not applicable');
        return false;
    }

Also: you could take $(this).val() out to a variable at the beginning, so you're not checking it ever time. So just something like var currentVal = $(this).val(), and then reference that instead.

Here's a fiddle: Fiddle

like image 21
Colin DeClue Avatar answered Sep 29 '22 16:09

Colin DeClue