How do I change an HTML selected option using JavaScript? 1

How do I change an HTML selected option using JavaScript?

change

function selectItemByValue(elmnt, value){

  for(var i=0; i < elmnt.options.length; i++)
  {
    if(elmnt.options[i].value === value) {
      elmnt.selectedIndex = i;
      break;
    }
  }
}

Here is what the above code is Doing:
1. It's creating a function called selectItemByValue.
2. It's taking two parameters: the element and the value.
3. It's looping through the options in the drop down list.
4. It's checking if the value of the option is equal to the value that we want to select.
5. If the values are equal, it's setting the selectedIndex of the drop down list to the index of the option.
6. It's breaking out of the loop.

Now, let's see how we can use this function.

Similar Posts