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. ...

Get jQuery and JavaScript Phrasebook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.