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);
}
HTML
Javascript
Demo
Manipulate the DOM using
remove
andadd
on the select object. You can see http://www.w3schools.com/jsref/dom_obj_select.asp for more info.For add new options to some select element I have write the following code:
Vanilla JS solution
If you already have a set of options