2010-08-10 26 views
43

Estoy intentando completar una selección desplegable con una matriz usando jQuery.Rellenar lista desplegable seleccionar con una matriz usando jQuery

Aquí está mi código:

 // Add the list of numbers to the drop down here 
     var numbers[] = { 1, 2, 3, 4, 5}; 
     $.each(numbers, function(val, text) { 
      $('#items').append(
       $('<option></option>').val(val).html(text) 
      );    
     // END 

Pero estoy recibiendo un error. Cada función es algo que obtengo de este sitio web.

¿Está bombardeando porque estoy usando una matriz unidimensional? Quiero que la opción y el texto sean iguales.

+0

artículos Al añadir uno a la vez en el DOM se considera que es muy lento y es altamente advised_ _not. ¿De manera más realista es construir una cadena y anexarla después de que el ciclo –

Respuesta

78

Trate de bucles:

var numbers = [1, 2, 3, 4, 5]; 

for (var i=0;i<numbers.length;i++){ 
    $('<option/>').val(numbers[i]).html(numbers[i]).appendTo('#items'); 
} 

enfoque mucho mejor:

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); 
+0

no funciona para mí? – Syno

+0

Si la matriz con la que trata no son números o no provienen de una fuente segura, debe usar la primera técnica enumerada, excepto que use '.text (número [i])' en lugar de '.html (número [i])'. Esto asegurará que no se arriesgue a ningún exploit de inyección. – webwake

36

La declaración de matriz tiene una sintaxis incorrecta. Intente lo siguiente, en su lugar:

var numbers = [ 1, 2, 3, 4, 5] 

La parte derecha de bucle parece

$.each(numbers, function(val, text) { 
      $('#items').append($('<option></option>').val(val).html(text)) 
      }); // there was also a) missing here 

Como hizo @Reigel parece añadir un poco más de rendimiento (que no es notable en este tipo de arreglos pequeños)

+0

Esta es la mejor opción si tiene claves predefinidas – RSM

5

también puede hacer esto:

var list = $('#items')[0]; // HTMLSelectElement 
$.each(numbers, function(index, text) { 
    list.options[list.options.length] = new Option(index, text); 
}); 
0
function validateForm(){ 
    var success = true; 
    resetErrorMessages(); 
    var myArray = []; 
    $(".linkedServiceDonationPurpose").each(function(){ 
     myArray.push($(this).val()) 
    }); 

    $(".linkedServiceDonationPurpose").each(function(){ 
    for (var i = 0; i < myArray.length; i = i + 1) { 
     for (var j = i+1; j < myArray.length; j = j + 1) 
      if(myArray[i] == myArray[j] && $(this).val() == myArray[j]){ 
       $(this).next("div").html('Duplicate item selected'); 
       success=false; 
      } 
     } 
    }); 
    if (success) { 
     return true; 
    } else { 
     return false; 
    } 
    function resetErrorMessages() { 
     $(".error").each(function(){ 
      $(this).html(''); 
     });`` 
    } 
} 
0

La solución que utilicé fue crear una función javascript que utilizara jquery:

Esto rellenará un objeto desplegable en la página HTML. Por favor, hágame saber dónde se puede optimizar esto, pero funciona bien tal como está.

function util_PopulateDropDownListAndSelect(sourceListObject, sourceListTextFieldName, targetDropDownName, valueToSelect) 
{ 
    var options = ''; 

    // Create the list of HTML Options 
    for (i = 0; i < sourceListObject.List.length; i++) 
    { 
     options += "<option value='" + sourceListObject.List[i][sourceListTextFieldName] + "'>" + sourceListObject.List[i][sourceListTextFieldName] + "</option>\r\n"; 
    } 

    // Assign the options to the HTML Select container 
    $('select#' + targetDropDownName)[0].innerHTML = options; 

    // Set the option to be Selected 
    $('#' + targetDropDownName).val(valueToSelect); 

    // Refresh the HTML Select so it displays the Selected option 
    $('#' + targetDropDownName).selectmenu('refresh') 
} 

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
2
var qty = 5; 
var option = ''; 
for (var i=1;i <= qty;i++){ 
    option += '<option value="'+ i + '">' + i + '</option>'; 
} 
$('#items').append(option); 
2

Una solución es crear su propio plugin de jQuery que tome el mapa JSON y poblar el selecto con él.

(function($) {  
    $.fn.fillValues = function(options) { 
     var settings = $.extend({ 
      datas : null, 
      complete : null, 
     }, options); 

     this.each(function(){ 
      var datas = settings.datas; 
      if(datas !=null) { 
       $(this).empty(); 
       for(var key in datas){ 
        $(this).append('<option value="'+key+'"+>'+datas[key]+'</option>'); 
       } 
      } 
      if($.isFunction(settings.complete)){ 
       settings.complete.call(this); 
      } 
     }); 

    } 

}(jQuery)); 

Se le puede llamar al hacer esto:

$("#select").fillValues({datas:your_map,}); 

las ventajas es que en cualquier lugar que se enfrentará el mismo problema que acaba de llamar

$("....").fillValues({datas:your_map,}); 

Et voilá!

Puede agregar funciones en su plugin como desee

Cuestiones relacionadas