multiple select comparison using jQuery

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

multiple select comparison using jQuery

vivekmyself
Hi ,

Im using jquery.validate.js. I need to compare 2 multiple select fields using jquery validation. If both the selected fields are same it should through an error message.

This is the sample html code
Multiselcet 1
<select multiple="multiple" name="cases" id="cases" size="5" >
                <option value="o1">Option 1</option>
                <option value="o2">Option 2</option>
                <option value="o3">Option 3</option>
                <option value="o4">Option 4</option>
                <option value="o5">Option 5</option>
                <option value="o6">Option 6</option>
              </select>

Multiselect 2

<select multiple="multiple" name="control" id="control" size="5" >
                <option value="o1">Option 1</option>
                <option value="o2">Option 2</option>
                <option value="o3">Option 3</option>
                <option value="o4">Option 4</option>
                <option value="o5">Option 5</option>
                <option value="o6">Option 6</option>
              </select>

Now the comparison is done by javascript, I need to convert this into jquery function.

Javascript function

function check_listbox(opt1,opt2){

var cases = new Array();
var control = new Array();
var index = 0;

//Populate the array for storing all the case files.

            for (var intLoop = 0; intLoop < opt1.length; intLoop++) {
               if ((opt1[intLoop].selected) ||
                   (opt1[intLoop].checked)) {
                       index = cases.length;
                  cases[index] = new Object;
                  cases[index].value = opt1[intLoop].value;
                  cases[index].index = intLoop;
               }
            }

index = 0;
//Populate the array for storing all the control files.
           
            for (intLoop = 0; intLoop < opt2.length; intLoop++) {
               if ((opt2[intLoop].selected) ||
                   (opt2[intLoop].checked)) {
                   index = control.length;
                  control[index] = new Object;
                  control[index].value = opt2[intLoop].value;
                  control[index].index = intLoop;
               }
            }

//Comparing each case and control files and throwing an error if they are same.
        for (var i = 0; i < cases.length; i++) {
            for (var j = 0; j < control.length; j++) {
                if (cases[i].value == control[j].value ) {
                    alert("You have selected the same files for case and control.Please select different files");
                    return false;  
                }
            }
        }
        return true;
}