2010-08-10 11 views
43

Sto tentando di compilare un menu a discesa con un array utilizzando jQuery.Populate dropdown select with array using jQuery

Ecco il mio codice:

 // 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 

Ma io sto ottenendo un errore. Ogni funzione è qualcosa che ho trovato su questo sito.

Bombarda perché utilizzo un array monodimensionale? Voglio che sia l'opzione che il testo siano gli stessi.

+0

articoli aggiungendo la prima volta sul DOM è considerato essere molto lento ed è altamente advised_ _non. Molto più performante è costruire una stringa e aggiungerla dopo il ciclo –

risposta

78

provare per cicli:

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

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

approccio Molto meglio:

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

non funziona per me? – Syno

+0

Se la matrice con cui si ha a che fare non è un numero o una sorgente sicura, si dovrebbe usare la 1a tecnica elencata eccetto l'uso di '.text (number [i])' invece di '.html (numero [i])'. Ciò garantirà che non si rischi alcun exploit di iniezione. – webwake

36

La dichiarazione di matrice ha una sintassi errata. Provare quanto segue, invece:

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

La parte del ciclo sembra giusto

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

Come ha fatto @Reigel sembra aggiungere un po 'più di prestazioni (non è visibile su tali piccoli array)

+0

Questa è l'opzione migliore se si dispone di tasti predefiniti – RSM

5

È anche possibile fare questo:

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 soluzione che ho usato è stata quella di creare una funzione javascript che utilizza jquery:

Questo popolerà un oggetto a discesa sulla pagina HTML. Per favore fatemi sapere dove questo può essere ottimizzato, ma funziona bene così com'è.

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 soluzione è quella di creare il proprio plugin per jQuery che prendono la mappa JSON e popolare la selezionare con esso.

(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)); 

Si può chiamare in questo modo:

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

vantaggi è che ovunque si troveranno ad affrontare lo stesso problema basta chiamare

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

Et voilà!

È possibile aggiungere funzioni nel vostro plugin come ti piace