开发者

Programmatically selecting options in IE

I have a little script that generates a select field and selects the appropriate option when it's generated. It looks a bit like this:

options.each(function (option) {
    var optionString = "<option id='" + option.id + "' value='" + option.value + "'>" + option.text + "</option>";
    $('selectField').insert(optionString);
    if(option.selected) {
        toBeSelected = option.id;
    }
});
$(toBeSelected).setAttribute('selected','selected');

Now the above script wo开发者_Python百科rks fine in Chrome and Firefox, but in IE it will always select the last element in the list. so say I was generating a list of options ['a','b','c','d'], 'd' would always be selected.

Does anybody have an idea what could be causing this?

UPDATE:

Okay, I found a solution to this, and it involved replacing the 'insert' with generating the option nodes manually, a bit like the following:

var newOption = document.createElement('option');
newOption.setAttribute('value',option.value);
newOption.innerHTML = option.text;
if(option.selected) {
    newOption.selected = true;
}

$('selectField').appendChild(newOption);

I'm guessing the issue lied with how the prototype insert() works, although I'm just glad the problem is solved.

I'll reformat this as an answer once the 8 hours are up to answer my own question.

Thankyou all for your input in this


var options = new Array();

options.push({id:1,value:'one',text:'text1',selected:false});
options.push({id:2,value:'two',text:'text2',selected:true});
options.push({id:3,value:'three',text:'text3',selected:false});
options.push({id:4,value:'four',text:'text4',selected:false});

var toBeSelected;
options.each(function(option) {
    var optionString = "<option id='" + option.id + "' value='" + option.value + "'>" + option.text + "</option>";
    $('selectField').insert(optionString);
    if (option.selected == true)
    {
        toBeSelected = option.id+""; // +"" because have to be a string
    }
});

$(toBeSelected).selected = true;


Okay, I found a solution to this, and it involved replacing the 'insert' with generating the option nodes manually, a bit like the following:

var newOption = document.createElement('option');
newOption.setAttribute('value',option.value);
newOption.innerHTML = option.text;
if(option.selected) {
    newOption.selected = true;
}

$('selectField').appendChild(newOption);

I'm guessing the issue lied with how the prototype insert() works, although I'm just glad the problem is solved.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜