开发者

To set one value in a dropdown list as top one from an array of values : jquery

开发者 https://www.devze.com 2023-04-11 18:39 出处:网络
I have a dropdownlist in jquery. I\'m filling that dropdown using an array. I want to 开发者_开发问答set one of the values as the first in the list from an array of values.

I have a dropdownlist in jquery. I'm filling that dropdown using an array. I want to 开发者_开发问答set one of the values as the first in the list from an array of values. Say i have 'a','b','c' in an array and i want to set 'b' as the first in the array.

Many thanks in advance..


$('select option:eq(1)').prop('selected', true);

where 1 is the index of 'b' inside of your array.


If you want to set one option as "SELECTED you just have to add it to html like this:

<option value='your' SELECTED>Name</option>

This will make this option the first of the list or the selected one. Otherwise the options will follow the order you gave them

<option value='your1'>Name1</option>
<option value='your2'>Name1</option>

in this case Name1 will appear before Name2


set the property selected="selected" in the <option> tag for that specific value


You could reorder the array by using a combination of array.splice() and array.concat(). Then do your binding as normal. e.g.

var foo = ['a', 'b', 'c'];
var bar = foo.splice(1,1); // the first arg is the index of the item to remove
var baz = bar.concat(foo); // baz contains the new array with the 'b' value in the first spot


John stickers soloution is good.

If you want to do it with text and not an index, you could do:

    //BUILD ARRAY
    var fruits = ["Banana", "Orange", "Apple", "Mango"];

    //BUILD DROPDOWN
    var firstItem = "Mango";
    var buildHTML = "";
    $.each( fruits, function(intIndex, objValue){ 
        if(objValue != firstItem) {
            buildHTML += "<option>"+objValue+"</option>";
        } else {
            buildHTML = "<option>"+objValue+"</option>"+buildHTML;
        }
    });
    $("#dropdownbox").append(buildHTML);

And have an empty selectbox

<select id="dropdownbox">
</select>


I tried and found out the answer:

$("#selectControl").attr('selectedIndex',indexVal);

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号