Skip to content Skip to sidebar Skip to footer

Javascript: Add Extra Attribute After New Option()

I have a piece of code that dynamically adds options to a select field depending on some other criteria. It looks somewhat like this: if (chosen == 'a_value') { selbox.options[se

Solution 1:

you can do something like

var o1 = new Option("key","value");
selbox.options[selbox.options.length] = o1;
o1.setAttribute("key","value");

Solution 2:

I know this is old but I came across this question when I forgot it's add and not push today.

The correct way is to use select.options.add.

var opt = document.createElement('option');
 opt.value = 'hello';
 opt.text = 'world';
 opt.setAttribute('data-discount', 'integer');
 selbox.options.add(opt);

Solution 3:

You can combine this into one line of code:

(selbox.options[selbox.options.length] = newOption("key","value")).setAttribute("key","value");

Note that this will only work if you have just one attribute to add, otherwise you will need a temporary variable.

Post a Comment for "Javascript: Add Extra Attribute After New Option()"