2012-06-06 13 views
86

que tienen menú de opciones como esto:¿Cómo cambio una opción HTML seleccionada con JavaScript?

<form name="AddAndEdit"> 
    <select name="list" id="personlist"> 
     <option value="11">Person1</option> 
     <option value="27">Person2</option> 
     <option value="17">Person3</option> 
     <option value="10">Person4</option> 
     <option value="7">Person5</option> 
     <option value="32">Person6</option> 
     <option value="18">Person7</option> 
     <option value="29">Person8</option> 
     <option value="28">Person9</option> 
     <option value="34">Person10</option> 
     <option value="12">Person11</option> 
     <option value="19">Person12</option> 
    </select> 
</form> 

y ahora quiero cambiar la opción seleccionada mediante el uso de un href. Por ejemplo:

<a href="javascript:void(0);" 
    onclick="document.getElementById('personlist').getElementsByTagName('option')[11].selected = 'selected';">change</a> 

Pero quiero seleccionar la opción con value=11 (Person1), no Person12.

¿Cómo cambio este código?

Respuesta

136

Cambio

document.getElementById('personlist').getElementsByTagName('option')[11].selected = 'selected' 

a

document.getElementById('personlist').value=Person_ID; 
+0

¿Cómo funciona esto con valores múltiples? Por ejemplo: 'document.getElementById ('personlist'). Value = id1, id2' no funcionará, ¿cómo gestionar eso? – utdev

+1

@utdev aquí hay una solución para la selección múltiple http://stackoverflow.com/a/1296068/1251563 sugerencia: necesita utilizar un bucle – breq

+0

Así que no puedo hacer algo como '.value = id1, id2' o '.value = [matriz]'? – utdev

1

Una matriz Índice comenzará a partir de 0. Si desea valor = 11 (Persona1), obtendrá con la posición getElementsByTagName('option')[10].selected.

19

Creo que la publicación del blog JavaScript Beginners – Select a dropdown option by value podría ayudarlo.

<a href="javascript:void(0);" onclick="selectItemByValue(document.getElementById('personlist'),11)">change</a> 

function selectItemByValue(elmnt, value){ 

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

Probablemente debería 'romper 'fuera de su bucle una vez que haya encontrado el valor seleccionado. Ahorra tiempo si la lista es larga y el valor objetivo es uno de los primeros. – megaflop

16

Estas son todas las herramientas como código JavaScript puro para el manejo de selectbox:

Fiddler DEMO

Código JavaScript:

/** 
* Empty Select Box 
* @param eid Element ID 
* @param value text 
* @param text text 
* @author Neeraj.Singh 
*/ 
function emptySelectBoxById(eid, value, text) { 
    document.getElementById(eid).innerHTML = "<option value='" + value + "'>" + text + "</option>"; 
} 


/** 
* Reset Select Box 
* @param eid Element ID 
*/ 

function resetSelectBoxById(eid) { 
    document.getElementById(eid).options[0].selected = 'selected'; 
} 


/** 
* Set Select Box Selection By Index 
* @param eid Element ID 
* @param eindx Element Index 
*/ 

function setSelectBoxByIndex(eid, eindx) { 
    document.getElementById(eid).getElementsByTagName('option')[eindx].selected = 'selected'; 
    //or 
    document.getElementById(eid).options[eindx].selected = 'selected'; 
} 


/** 
* Set Select Box Selection By Value 
* @param eid Element ID 
* @param eval Element Index 
*/ 
function setSelectBoxByValue(eid, eval) { 
    document.getElementById(eid).value = eval; 
} 


/** 
* Set Select Box Selection By Text 
* @param eid Element ID 
* @param eval Element Index 
*/ 
function setSelectBoxByText(eid, etxt) { 
    var eid = document.getElementById(eid); 
    for (var i = 0; i < eid.options.length; ++i) { 
     if (eid.options[i].text === etxt) 
      eid.options[i].selected = true; 
    } 
} 


/** 
* Get Select Box Text By ID 
* @param eid Element ID 
* @return string 
*/ 

function getSelectBoxText(eid) { 
    return document.getElementById(eid).options[document.getElementById(eid).selectedIndex].text; 
} 


/** 
* Get Select Box Value By ID 
* @param eid Element ID 
* @return string 
*/ 

function getSelectBoxValue(id) { 
    return document.getElementById(id).options[document.getElementById(id).selectedIndex].value; 
} 
+0

¡Gran ejemplo de cómo interactuar con un selecto con javascript puro! –

10

También puede cambiar select.options .selectedIndex atributo DOM como este:

function selectOption(index){ 
 
    document.getElementById("select_id").options.selectedIndex = index; 
 
}
<p> 
 
<select id="select_id"> 
 
    <option selected>first option</option> 
 
    <option>second option</option> 
 
    <option>third option</option> 
 
</select> 
 
</p> 
 
<p> 
 
    <button onclick="selectOption(0);">Select first option</button> 
 
    <button onclick="selectOption(1);">Select second option</button> 
 
    <button onclick="selectOption(2);">Select third option</button> 
 
</p>

1

mySelect.value = myValue

Eso sí, mySelect.value = myValue donde myValue es igual al atributo de valor de la opción que desea ajustar a.

Cuestiones relacionadas