简体   繁体   中英

Create select DOM object with options in jQuery, Passing Attributes

How can I create a select DOM object with options in jquery similar to this input creation example?

$('<input />', {
  name: 'age',
  type: 'number',
  placeholder: 'enter a number 1'
}).appendTo('#app');

Is there a way to create it passing attributes?

You can create just by passing the entire select with option as string

$('<select name="number">' +
  '<option>1</option>' +
  '<option>2</option>' +
  '<option>3</option>' +
'</select>').appendTo('body');

Another solution, using an array of objects having the required value and text and creating new select element based on the array information.

 $(document).ready(function () { var arrSelect = [ { value: 1, text: 'One' }, { value: 2, text: 'Two' }, { value: 3, text: 'Three' } ]; var select = $('<select>').appendTo('body'); //Create new select element //Loop through the array of objects and then create new option and append to select element arrSelect.map(function (arr) { select.append($("<option>").attr('value', arr.value).text(arr.text)) }); $("body").append(select); //Append select to body element }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> 

When creating an element with jQuery, any attribute, or even jQuery method, can be used in the options object, so you can do

 $('<select />', { name : 'test', on : { change : function() { /* stuff */ } }, append : [ $('<option />', {value : "1", text : "Opt 1"}), $('<option />', {value : "2", text : "Opt 2"}), $('<option />', {value : "3", text : "Opt 3"}) ] }).appendTo('#app'); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="app"></div> 

1_ you can select Multiple DOM Multi DOM Select

like so :

$( "div, .sCLASS, p.myClass" ).whatever...

2_ you can also select Single DOM with concate Single DOM Select

like so :

$( "p" + ".sCLASS" ).whatever...

BUT you can't pass arg with it

The object select is created and then the options objects are appended.

$('<select />', {
  id: 'my-numbers',
  name: 'select-number'
})
.append($("<option/>", {
    value: '1',
    text: 'number1'
}))
.append($("<option/>", {
    value: '2',
    text: 'number2'
}))
.appendTo('#app');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM