O'Reilly logo

jQuery and JavaScript Phrasebook by Brad Dayley

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Dynamically Creating a Select Form Element

var select = $("<select></select>"); var opt = $("<option></option"); opt.val("1"); opt.html("Option 1"); select.append(opt); select.val(opt.val());

jQuery makes it easy to dynamically generate a select element. This is useful if you are trying to add selects with a large number of options or if the data for the select is coming in a dynamic way, such as user input or an AJAX request.

To dynamically create a select, you first need to create a <select> element using the following code:

var select = $("<select></select>");

Then you need to add options by creating the <option> element, setting a value for the option, and then defining the HTML to appear in the select. ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required