Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check existence of values in array on multi select dropdown focusout in jQuery

i have a default array that have some fixed values from which i am showing a multiselect dropdown to user.So on focusout of the drop down i want to check that whether the values are selected have the all those values that are in the default array.If the values are missing i want to alert them to the user

HTML

<form action="#" method="post">
    <fieldset>
        <label for="selectedItemLists">Select values:</label>
        <select id="selectedItemLists" name="selectedItemLists" multiple>
            <option val="value1" selected >value1</option>
            <option val="value2">value2</option>
            <option val="value3" selected>value3</option>
            <option val="value4">value4</option>
            <option val="value5">value5</option>
        </select>
    </fieldset>
    <fieldset>
        <input type="submit" value="submit" />
    </fieldset>
</form>

jQuery

var default_values = ["value1","value3"];

$("#selectedItemLists").live('focusout',function(){
    var new_selectedvalues = $("#selectedItemLists").val();

    //here i want to compare both the arrays and alert him that default values are missing
});
like image 998
Developer Avatar asked Nov 10 '22 05:11

Developer


1 Answers

A simple nested $.each loop will do it:

Demo

//here i want to compare both the arrays and alert him that default values are missing
$.each(default_values, function(_, defaultVal){
    var found = false;
    $.each(new_selectedvalues, function(){
        if(this == defaultVal){
            found = true;
            return false;
        }
    });

    if(!found){
        alert("Please select the default: " + defaultVal);   
    }
});

Note: .live() is deprecated from jQuery 1.7, so .on should be used instead (unless you are working with the old version).

like image 92
MrCode Avatar answered Nov 14 '22 23:11

MrCode