Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Browser Neutral Way to add options to a select element in javascript

Tags:

javascript

I just learned something interesting. The add method for the javascript select object in IE 6 takes only one parameter. It throws an error when you pass it two parameters which I believe is the standard, even as documented on the MSDN site.

My question is this. What is your best-practice recommendation for programmatically adding option elements to a select element in javascript?

  • Call the add method differently based on the value of the user agent?
  • Wrap the select object in a class that provides the proper method signature?
  • Use a javascript library which does this for you (specify which library)?
like image 482
Glenn Avatar asked Nov 15 '08 03:11

Glenn


People also ask

How add option tag dynamically to select in jQuery?

Method 1: Append the option tag to the select box The select box is selected with the jQuery selector and this option is added with the append() method. The append() method inserts the specified content as the last child of the jQuery collection. Hence the option is added to the select element.

How can I give an array as options to select element?

To set a JavaScript array as options for a select element, we can use the options. add method and the Option constructor. to add the select drop down. to select the select element with querySelector .


1 Answers

Adding a new Option type works at least IE6 and up

function addOption(selectID, display, value)
{
  var obj = document.getElementById(selectID);
  obj.options[obj.options.length] = new Option(display, value);
}

Additionally tested in Firefox 2, 3, Opera 8, 9.5, and Safari 4 successfully. IE4 failed :(

like image 111
Elle H Avatar answered Oct 27 '22 00:10

Elle H