Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select dropdown menu option with javascript

I have a dropdown menu and I cannot figure out how to make a javascript function select a drop down menu option. I have tested the output of the variables and they are all correct, but it still will not select the option when clicked. Here is the function and drop down menu.

Function

function formFill(a, b, c){         theform.from.value = a;         theform.to.value = b;         for(var i = 0;i < document.getElementById("stateSelect").length;i++){             if(document.getElementById("stateSelect").options[i].value == c ){                 document.getElementById("stateSelect").selected = true;             }         }     } 

Menu item

<select id="stateSelect" name="stateSelect">     <option value="none">(None)</option>     <option value="AL">Alabama</option>     <option value="AK">Alaska</option> 
like image 644
shinjuo Avatar asked Apr 15 '11 14:04

shinjuo


People also ask

How do you create a drop-down list in JavaScript?

The <select> tab is used with <option> tab to create the simple dropdown list in HTML. After that JavaScript helps to perform operation with this list. Other than this, you can use the container tab <div> to create the dropdown list. Add the dropdown items and links inside it.

How do you select in JavaScript?

To select a <select> element, you use the DOM API like getElementById() or querySelector() . How it works: First, select the <button> and <select> elements using the querySelector() method. Then, attach a click event listener to the button and show the selected index using the alert() method when the button is clicked.

How do I select a value from a dropdown in HTML?

The select tag in HTML is used to create a dropdown list of options that can be selected. The option tag contains the value that would be used when selected. The default value of the select element can be set by using the 'selected' attribute on the required option. This is a boolean attribute.


1 Answers

Change the line that reads:

document.getElementById("stateSelect").selected = true;

to:

document.getElementById("stateSelect").selectedIndex = i;

like image 96
David Hancock Avatar answered Sep 25 '22 12:09

David Hancock