简体   繁体   中英

Setting the selected index after populating a dropdown list via ajax call

I am populating a select tags options via an ajax call and after that I try to set the selected item in the drop down list using javascript. But it doesn't seem to be working.

In my Index.cshtml page i have the select tag like this

<select id="ddlState">
</select>

On the same page I use an ajax call to populate the options list.

$.ajax({
    url: "/api/vmsApi",
    success: function (data) {
        console.log(data)
        for (var i = 0; i < data.length; i++)
        {
            $("#ddlState").append('<option value="'+data[i]+'">' + data[i]+ '</option>')
        }
    }
});

Then as a test I tried to set the selectedIndex to something greater than 0.. like below:

document.getElementById("ddlState").selectedIndex = 2;

No matter what value I give for the selected index.. the first item is always selected....

Why is this?

My drop down list does get populated with all the values. just the selectedIndex wont change.

Are you sure the following does not work?

$.ajax({
    url: "/api/vmsApi"
})
.then(
  (data) => {
        console.log(data);
        const select = $("#ddlState");
        data.forEach(
          data =>
            select.append(
              '<option value="'+
              data+
              '">'
              + data
              + '</option>'
          )
        );
        select[0].selectedIndex = 2;
    }
)
.then(
  undefined
  ,reject => console.error(reject)
);

If this does not work could you please use the dev tools in chrome (F12) in the console tab press control + shift + f and look for selectedIndex maybe there is some other code on your page that sets selected index.

To address your comment: the console shows values as they were if it fits in the console.

When you need to expand a value then it shows the value as it is now, not as it was when you console logged it. you can run the following code in devtools console and see for yourself:

var i = 0;
var arr = [];
while(++i<300){
  arr.push({value:i});
}
console.log("shows new values when you expand even though the log was before the change:",arr)
console.log("shows old value because no need to expand:",arr[0])
arr.forEach(x => x.value += 10);
console.log("shows new values because it is executed after change:",arr)

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