简体   繁体   中英

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.

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.

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, (ie, 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

Here's another option. This code is less efficient than the other answers since it will always iterate.

jQuery has two varieties of $.each(array, function(index, value)... This works similar to your current loops.

var fields = new Array();
$("#dataTable tr select[name^='dRelation']").each(function(i){
    fields.push(this.value);
 });
var rel = $(this).val();
$.each(fields, function(i,val) {
    if((val=='Son' || val=='Father') && (rel == 'Father-in-law' || rel == 'Mother-in-law'))                                 
        alert("yep");
 });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM