Adding options to a select and selecting one on internet explorer

后端 未结 3 1939
梦如初夏
梦如初夏 2021-01-15 01:02

I have a select, and I am filling the options using javascript. Something like

    var select = document.getElementById(\"selectBox\");

    for (var i = 0;          


        
相关标签:
3条回答
  • 2021-01-15 01:32

    The problem was where I was getting the selected value from. I was using ajax calls, and IE was (I think) caching the response. When I changed some value, the server had to give me the correct select option, but it was giving me wrong one since IE was always reading the same answer.

    0 讨论(0)
  • 2021-01-15 01:35

    You can try this

    Javascript

    var select = document.getElementById("selectBox"),
        data = [{ name: "y", id: "b" }, { name: "z", id: "c" }],
        i;
    
    for (i = 0; i < data.length; i += 1) {
        var option = document.createElement("option");
        
        option.appendChild(document.createTextNode(data[i].name));
        // or alternately
        //option.text = data[i].name;
        option.value = data[i].id;
        select.appendChild(option);
    }
    

    On jsfiddle

    And of course there is the standards compliant method HTMLOptionElement.Option() as described by @MaxArt

    0 讨论(0)
  • 2021-01-15 01:52

    Use add instead of appendChild:

    select.add(option);
    

    Also, using the Option constructor can save you some lines of code:

    var option = new Option(data[i].name, data[i].id);
    
    0 讨论(0)
提交回复
热议问题