J19
J19

Reputation: 717

Selecting an item in a Dropdown control from javascript no jQuery

I'm using Office UI Fabric and I'm using a ms-Dropdown control. From javascript, I'm trying to select and item

<div class="ms-Dropdown" tabindex="0">
  <label class="ms-Label" style="font-size: 14px; font-weight: 600;">My Options</label>
  <i class="ms-Dropdown-caretDown ms-Icon ms-Icon--ChevronDown"></i>
  <select id="myoptions" class="ms-Dropdown-select">
    <option>Choose an option&amp;hellip;</option>
    <option>One</option>
    <option>Two</option>
  </select>
</div>

From Javascript, I run

document.getElementById("myoptions").value = "Two";

or

document.getElementById("myoptions").selectedIndex = 2;

Both don't work properly. The UI don't refresh with the new selected option.

Any idea how can I select an item from Javascript (no jQuery)?

Upvotes: 0

Views: 315

Answers (3)

becher henchiri
becher henchiri

Reputation: 667

Use this solution :

 //set item index
 var option = document.getElementById("myoptions").item(2)
 option.setAttribute("selected",true)
 
 
 
 
 
   <div class="ms-Dropdown" tabindex="0">
  <label class="ms-Label" style="font-size: 14px; font-weight: 600;">My Options</label>
  <i class="ms-Dropdown-caretDown ms-Icon ms-Icon--ChevronDown"></i>
  <select id="myoptions" class="ms-Dropdown-select">
    <option>Choose an option&amp;hellip;</option>
    <option >One</option>
    <option >Two</option>
  </select>
</div>

Upvotes: 1

sdn404
sdn404

Reputation: 624

try this:

document.getElementById("myoptions").options.selectedIndex = 2;

Upvotes: 0

Clarity
Clarity

Reputation: 10873

Your options are missing values:

 <select id="myoptions" class="ms-Dropdown-select">
    <option value=''>Choose an option&amp;hellip;</option>
    <option value='One'>One</option>
    <option value='Two'>Two</option>
  </select>

Upvotes: 1

Related Questions