简体   繁体   中英

Populate dropdown select with array-with multiple options

So I'm trying to populate a dropdown with the states, the value for the option should be the two characters value, and the text for the option should be the full state's name, using the code below is returning a value of 0,1,2,3... and returning all the options in the var as the text.

var states = ["Select State","","Alabama","AL","Alaska","AK","Arizona","AZ","Arkansas","AR",...];
$.each(states, function(val, text) {
    $('#selector').append( $('<option> </option>').val(val).html(text) )
    });

Try this, using an object for states instead of an array. Same results, but it's more clear what's what and you're less likely to have problems if you accidentally skip a name or abbreviation:

var states = {
    "Select State":"", 
    "Alabama":"AL", 
    "Alaska":"AK", 
    "Arizona":"AZ",  
    "Arkansas":"AR" 
};
var val, text;
for (text in states) {
    val = states[text];
    $('<option/>').val(val).text(text).appendTo($('#selector'));
};

http://jsfiddle.net/g59U4/

I have a similar situation populating a select list with a two-dimensional array as the result of an $.ajax callback ....

JSON ...     
[["AL","Alabama"],["AK","Alaska"],["AS","American Samoa"],["AZ","Arizona"] ... 

var stateOptions = $('#state');
var html ='';
for (var i =1; i<data.length; i++){
    html+= '<option value="' +data[i][0]+ '">' +data[i][1]+ '</option>';
}
stateOptions.append(html);

<form name="form" id="form">

<select name="state" id="state">
        <option value=''>State</option>
</select>

</form>

The problem is that the callback function provided to .each results in val containing the index of the current iteration (eg 0, 1, 2 etc.) and text containing the value of that index of the array.

To achieve what you are trying to, you would probably be better off with a normal for loop:

for(var i = 0; i < states.length; i+=2) {
    $("#selector").append($('<option> </option>').val(states[i+1]).html(states[i]));  
}

You would be even better off caching the jQuery object containing #selector outside of your loop, so it doesn't have to look it up every iteration.

Here's a working example of the above.

Another option would be to use an object instead of an array, using the state name or abbreviation as the keys, and the other as the values. Edit: just like @mblase75 has done

Well you have the jQuery.each function arguments confused. The first is the index of the value in the array, and the second in the value itself. What you need to do is something like:

$.each(states, function(index) {
    if(index%2 > 0) {
        //continue, basically skip every other one. Although there is probably a better way to do this
        return true;
    }
    $('#selector').append( $('<option> </option>').val(states[index+1]).html(states[index]) )
});

That would be really straightforward if your array had two dimensions. Considering you really need to use the one-dimensional array you presented, you could do this:

var states = ["Select State","","Alabama","AL","Alaska","AK","Arizona","AZ","Arkansas","AR"];
for(var i=1; i<states.length; i+=2) {
    $('#selector').append( $('<option value="' + states[i] + '">' + states[i-1] + '</option>').val(val).html(text) )
}

If you changed your array to be an array of objects, you could do something like this -

var states = [{"text":"Select State","val":""},{"text":"Alabama","val":"AL"}]; //etc
$.each(states, function(val, statedata) {
    $('#selector').append( $('<option> </option>').val(statedata.val).html(statedata.text) )
});

This change passes a JavaScript object in to the callback each time. The object has text and val properties and is passed in to the callback as the statedata parameter. The val parameter holds the current index position of the array so it is not required to populate the select box.

Demo - http://jsfiddle.net/sR35r/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM