Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

javascript - Change the options array of a select list

Is there a way to change the options array of an html select list using javascript or mootools?

I need to replace the entire options set with a new one. In my ajax response I receive an array filled in with with the new HTML options, so I try to empty the old list and add new values as follows

$('element').options.length=0;
for (i=0; i<newSet.length; i++)
{
    $('element').options[i]=newSet[i];
}

The above code gives me an uncaught exception on the line inside the loop.

uncaught exception: [Exception... "Unexpected error" nsresult: "0x8000ffff (NS_ERROR_UNEXPECTED)" location: "JS frame

Just to add what worked for me:

/* get new options from json*/
var new_options = response.options;

/* Remove all options from the select list */
$('idresource').empty();
/* Insert the new ones from the array above */
for (var key in new_options)
{
var opt = document.createElement('option');
    opt.text = new_options[key];
    opt.value = key;
    $('idresource').add(opt, null);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
var new_options = ['Option 1', 'Option 2', 'Option 3'];

/* Remove all options from the select list */
$('yourSelectList').empty();

/* Insert the new ones from the array above */
$each(new_options, function(value) {
    new Element('option')
        .set('text', value)
        .inject($('yourSelectList'));
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...