Change the options array of a select list

Shakur picture Shakur · Jun 15, 2011 · Viewed 59.2k times · Source

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);
}

Answer

amit_g picture amit_g · Jun 16, 2011

HTML

<select class="element">
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>

<button><<<</button>

<select class="newSel">
    <option value="11">NewOne</option>
    <option value="22">NewTwo</option>
    <option value="33">NewThree</option>
</select>

Javascript

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

$("button").click(function(){
    var oldSel = $('.element').get(0);

    while (oldSel.options.length > 0) {
        oldSel.remove(oldSel.options.length - 1);
    }

    var newSel = $('.newSel').get(0);

    for (i = 0; i < newSel.length; i++)
    {
        var opt = document.createElement('option');

        opt.text = newSel.options[i].text;
        opt.value = newSel.options[i].value;

        oldSel.add(opt, null);
    }
})

Demo