Irfan Harun
Irfan Harun

Reputation: 1059

selecting value in dropdown by searching a keyword in array using javascript

 HTML PART
 <select id="carlist" name="cars">
 <option value="volvo">Volvo</option>
 <option value="fiat">Fiat</option>
 <option value="audi">Audi</option>
 </select>


 JAVASCRIPT PART
 cars=["volvo","fiat","audi"];
 var best = "fiat";
 for (var i=0;i<cars.length;i++)
 {
 if (cars.value == best.value)
 (
  document.getElementById('carlist').selectedIndex= 2;
  }

the final result of drop down is always audi because of the .selectIndex as 2 in the last line. What changes do i make in the last line so that the value of drop down changes according the variable " best" ??

Upvotes: 2

Views: 1135

Answers (2)

Prasath K
Prasath K

Reputation: 5018

cars=["volvo","fiat","audi"];
var best = "audi";
for (var i=0;i<cars.length;i++)
{
  if (cars[i] == best)
  {
    document.getElementById('carlist').selectedIndex= i;
  }
}

JS Fiddle

Upvotes: 4

PSR
PSR

Reputation: 40338

try this

  var selectobject=document.getElementById("carlist")
    for (var i=0; i<selectobject.length; i++){
    if(selectobject.options[i].value == best)
         ocument.getElementById('carlist').selectedIndex= i;
    }
    } 

Write this logic in for loop

or

cars=["volvo","fiat","audi"];
 var best = "fiat";
 for (var i=0;i<cars.length;i++)
     if (cars[i] == best)
       document.getElementById('carlist').selectedIndex= i;

Upvotes: 1

Related Questions