wootscootinboogie
wootscootinboogie

Reputation: 8695

Dynamically replace drop down menu options jQuery

I have a drop down menu whose select options I would like to change on a click event. The current select options should be removed and replaced with a new array of options. Here's the fiddle:

And here's another attempt at fixing it that doesn't work:

 $(document).ready(function () {
            var dropdown = $('<select>');
            dropdown.options = function (data) {
                var self = this;
                if (data.length > 0) {
                    //how to remove the current elements
                }
                $.each(data, function (ix, val) {
                    var option = $('<option>').text(val);
                    data.push(option);
                });
                self.append(data)
            }
            dropdown.clear = function () {
                this.options([]);
            }
            var array = ['one', 'two', 'three'];
            dropdown.options(array);
            $('body').append(dropdown);
            $('#btnSubmit').on('click', function (ix, val) {
                //should clear out the current options
                //and replace with the new array
                var newArray = ['four', 'five', 'six'];
                dropdown.clear();
                dropdown.options(newArray);
            });
        });

Upvotes: 3

Views: 15804

Answers (2)

Alireza Fattahi
Alireza Fattahi

Reputation: 45553

To clear the select use below code:

dropdown.empty();

http://jsfiddle.net/247z2/1/

Upvotes: 0

charlietfl
charlietfl

Reputation: 171689

All you have to do is change append() to html() since html() replaces existing content of element

 dropdown.options = function (data) {
            var self = this;
            $.each(data, function (ix, val) {
                var option = $('<option>').text(val).val(val);/* added "val()" also*/
                data.push(option);
            });
            self.html(data)
        }

DEMO

Upvotes: 4

Related Questions