una texto seleccionar seleccionado opcion obtener elemento desde dejar con javascript jquery

javascript - texto - ¿Agregar opciones a un<seleccionar> usando jQuery?



seleccionar un option desde javascript (27)

¿Cuál es la forma más fácil de agregar una option a un menú desplegable usando jQuery?

esto funcionara?

$("#mySelect").append(''<option value=1>My option</option>'');


Qué tal esto

var numbers = [1, 2, 3, 4, 5]; var option = ''''; for (var i=0;i<numbers.length;i++){ option += ''<option value="''+ numbers[i] + ''">'' + numbers[i] + ''</option>''; } $(''#items'').append(option);


Opción 1-

Puedes probar esto-

$(''#selectID'').append($(''<option>'', { value: value_variable, text : text_variable }));

Me gusta esto-

for (i = 0; i < 10; i++) { $(''#mySelect'').append($(''<option>'', { value: i, text : "Option "+i })); }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <select id=''mySelect''></select>

Opcion 2-

O prueba esto-

$(''#selectID'').append( ''<option value="''+value_variable+''">''+text_variable+''</option>'' );

Me gusta esto-

for (i = 0; i < 10; i++) { $(''#mySelect'').append( ''<option value="''+i+''">''+''Option ''+i+''</option>'' ); }

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <select id=''mySelect''></select>


Así es como lo hice, con un botón para agregar cada etiqueta de selección.

$(document).on("click","#button",function() { $(''#id_table_AddTransactions'').append(''<option></option>'') }


Basado en la respuesta de dule para agregar una colección de artículos, una frase for...in también funcionará de maravilla:

let cities = {''ny'':''New York'',''ld'':''London'',''db'':''Dubai'',''pk'':''Beijing'',''tk'':''Tokyo'',''nd'':''New Delhi''}; for(let c in cities){$(''#selectCity'').append($(''<option>'',{value: c,text: cities[c]}))}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.0/jquery.min.js"></script> <select id="selectCity"></select>

Tanto los valores de objeto como los índices se asignan a las opciones. ¡Esta solución funciona incluso en el antiguo jQuery (v1.4) !


Eso funciona bien.

Si agrega más de un elemento de opción, recomiendo realizar el anexo una vez en lugar de realizar un anexo en cada elemento.


Estas cosas muy simples. Puedes hacerlo de esta manera

$(''#select_id'').append(''<option value="five" selected="selected">Five</option>'');

o

$(''#select_id'').append($(''<option>'', { value: 1, text: ''One'' }));

Aquí está la guía completa


Esto NO funcionó en IE8 (pero sí en FF):

$("#selectList").append(new Option("option text", "value"));

Este trabajo DID:

var o = new Option("option text", "value"); /// jquerify the DOM object ''o'' so we can use the html method $(o).html("option text"); $("#selectList").append(o);


Esto es solo un punto rápido para el mejor rendimiento.

siempre que esté tratando con muchas opciones, cree una cadena grande y luego agréguela a ''seleccionar'' para obtener el mejor rendimiento

fg

var $ mySelect = $ (''# mySelect''); var str = '''';

$.each(items, function (i, item) { // IMPORTANT: no selectors inside the loop (for the best performance) str += "<option value=''" + item.value + "''> " + item.text + "</option>"; }); // you built a big string $mySelect.html(str); // <-- here you add the big string with a lot of options into the selector. $mySelect.multiSelect(''refresh'');

Aun más rápido

var str = ""; for(var i; i = 0; i < arr.length; i++){ str += "<option value=''" + item[i].value + "''> " + item[i].text + "</option>"; } $mySelect.html(str); $mySelect.multiSelect(''refresh'');


Hay dos maneras. Puedes usar cualquiera de estos dos.

Primero:

$(''#waterTransportationFrom'').append(''<option value="select" selected="selected">Select From Dropdown List</option>'');

Segundo:

$.each(dataCollecton, function(val, text) { options.append($(''<option></option>'').val(text.route).html(text.route)); });


Hemos encontrado algún problema al agregar la opción y usar la validación de jquery. Debe hacer clic en un elemento en la lista de selección múltiple. Agregará este código para manejar:

$("#phonelist").append("<option value=''"+ ''yournewvalue'' +"'' >"+ ''yournewvalue'' +"</option>"); $("#phonelist option:selected").removeAttr("selected"); // add to remove lase selected $(''#phonelist option[value='' + ''yournewvalue'' + '']'').attr(''selected'', true); //add new selected


Me gusta usar el enfoque no jQuery:

mySelect.add(new Option(''My option'', 1));


No se menciona en ninguna respuesta, pero es útil en el caso de que también desee seleccionar esa opción, puede agregar:

var o = new Option("option text", "value"); o.selected=true; $("#mySelect").append(o);


Para mejorar el rendimiento, debe intentar modificar el DOM solo una vez, incluso más si está agregando muchas opciones.

var html = ''''; for (var i = 0, len = data.length; i < len; ++i) { html.join(''<option value="'' + data[i][''value''] + ''">'' + data[i][''label''] + ''</option>''); } $(''#select'').append(html);


Personalmente, prefiero esta sintaxis para agregar opciones:

$(''#mySelect'').append($(''<option>'', { value: 1, text: ''My option'' }));

Si está agregando opciones de una colección de elementos, puede hacer lo siguiente:

$.each(items, function (i, item) { $(''#mySelect'').append($(''<option>'', { value: item.value, text : item.text })); });


Puede adjuntar y establecer el atributo Valor con texto:

$("#id").append($(''<option></option>'').attr("value", '''').text('''')); $("#id").append($(''<option></option>'').attr("value", ''4'').text(''Financial Institutions''));


Puede agregar opciones dinámicamente en el menú desplegable como se muestra en el siguiente ejemplo. Aquí, en este ejemplo, he tomado datos de matriz y he enlazado esos valores de matriz para desplegar como se muestra en la captura de pantalla de salida

Salida:

var resultData=["Mumbai","Delhi","Chennai","Goa"] $(document).ready(function(){ var myselect = $(''<select>''); $.each(resultData, function(index, key) { myselect.append( $(''<option></option>'').val(key).html(key) ); }); $(''#selectCity'').append(myselect.html()); });

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"> </script> <select id="selectCity"> </select>


Puede agregar opciones usando la siguiente sintaxis. También puede visitar la opción de manejo de manera en jQuery para obtener más detalles.

  1. $(''#select'').append($(''<option>'', {value:1, text:''One''}));

  2. $(''#select'').append(''<option value="1">One</option>'');

  3. var option = new Option(text, value); $(''#select'').append($(option));


Puedes hacer esto en ES6:

$.each(json, (i, val) => { $(''.js-country-of-birth'').append(`<option value="${val.country_code}"> ${val.country} </option>`); });


Puedes probar el siguiente código para agregar a la opción

<select id="mySelect"></select> <script> $("#mySelect").append($("<option></option>").val("1").html("My enter code hereoption")); </script>


Si desea insertar la nueva opción en un índice específico en la selección:

$("#my_select option").eq(2).before($(''<option>'', { value: ''New Item'', text: ''New Item'' }));

Esto insertará el "Nuevo elemento" como el tercer elemento en la selección.


Si el nombre o valor de la opción es dinámico, no tendrá que preocuparse por el escape de caracteres especiales en él; en esto usted puede preferir métodos simples de DOM:

var s= document.getElementById(''mySelect''); s.options[s.options.length]= new Option(''My option'', ''1'');


Si tiene optgroup dentro de select , u obtuvo un error en DOM.

Creo que una mejor manera:

$("#select option:last").after($(''<option value="1">my option</option>''));


por la razón que sea, haciendo $("#myselect").append(new Option("text", "text")); no me funciona en IE7 +

Tuve que usar $("#myselect").html("<option value=''text''>text</option>");


$(''#mySelect'').empty().append(''<option value=1>My option</option>'').selectmenu(''refresh'');


$(''#select_id'').append($(''<option>'',{ value: v, text: t }));


$(function () { var option = $("<option></option>"); option.text("Display text"); option.val("1"); $("#Select1").append(option); });

Si obtiene datos de algún objeto, simplemente reenvíe ese objeto para que funcione ...

$(function (product) { var option = $("<option></option>"); option.text(product.Name); option.val(product.Id); $("#Select1").append(option); });

Nombre e Id son nombres de propiedades de objeto ... así que puedes llamarlos como quieras ... Y, por supuesto, si tienes Array ... quieres crear una función personalizada con for loop ... y luego llamar a esa función documento listo ... Saludos


var select = $(''#myselect''); var newOptions = { ''red'' : ''Red'', ''blue'' : ''Blue'', ''green'' : ''Green'', ''yellow'' : ''Yellow'' }; $(''option'', select).remove(); $.each(newOptions, function(text, key) { var option = new Option(key, text); select.append($(option)); });