2011-04-15 80 views
19

Tengo un menú desplegable y no puedo entender cómo hacer una función de javascript seleccione una opción de menú desplegable. He probado el resultado de las variables y todas son correctas, pero aún así no seleccionarán la opción cuando se haga clic en ellas. Aquí está la función y el menú desplegable.Seleccionar la opción del menú desplegable con javascript

Función

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; 
      } 
     } 
    } 

Elemento de menú

<select id="stateSelect" name="stateSelect"> 
    <option value="none">(None)</option> 
    <option value="AL">Alabama</option> 
    <option value="AK">Alaska</option> 
+1

Usted no debe repetir 'document.getElementById ("stateSelect")'. Llámalo una vez y almacena la referencia en una variable. – RoToRa

+0

Consulte este artículo: http://javascriptstutorial.com/blog/selecting-dropdown-element-using-javascript-or-jquery/ –

Respuesta

29

Cambiar la línea que dice:

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

a:

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

+0

Impresionante, eso es lo que necesitaba. Gracias – shinjuo

+1

¿Por qué el '.selected' no funciona? – Coops

+1

Porque necesita saber qué elemento seleccionar. .selected es un get() que obtiene el estado seleccionado/no seleccionado, pero no puede establecer el estado porque no sabe qué elemento seleccionar. – Damienknight

12

Alt. puede establecer seleccionado a la opción real: select.options [i] .selected = true;

... 
     var select = document.getElementById("stateSelect"); 
     for(var i = 0;i < select.options.length;i++){ 
      if(select.options[i].value == c){ 
       select.options[i].selected = true; 
      } 
     } 
... 
Cuestiones relacionadas