Search code examples
javascriptjquerydrop-down-menudropdownbox

Loop through all the elements of select and add a blank option if the either of the items is null


I have 2 drop downs select1 and select2. I will select the item1 of select1 and then click OK button ( case in which I need help)

then if the selectedindex is 0 ( ie first option )then loop through the items of both drop downs.

if the same index elements ( eg 3rd element of both drop downs)are not null then execute some code and if either of them is null then execute some other code, how can I achieve this?

<select name="select1" id="select1"  multiple size="10">
    <option>1<option>
    <option>null<option>
    <option>null<option>
    <option>2<option>
    <option>3<option>
</select>
<select name="select2" id="select2"  multiple size="10">
    <option>4<option>
    <option>5<option>
    <option>6<option>
    <option>null<option>
    <option>10<option>
</select>

I tried this code but the fiddle become unresponsive.

http://jsfiddle.net/678hmujh/13/


Solution

  • As I can see in the comments. you are not breaking the loop after adding null when the first match is found.

    http://jsfiddle.net/678hmujh/19/ this works ok for me.

     if (optionS1[i].text != "null" && optionS2[i].text != "null") {
                 $(sel1).append("<option value=''>null</option>");
                 $(sel2).prepend("<option value=''>null</option>");
                 return;
             }