Jose Angel
Jose Angel

Reputation: 328

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?

Upvotes: 0

Views: 2489

Answers (5)

adeneo
adeneo

Reputation: 318372

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>

Upvotes: 1

Jose Angel
Jose Angel

Reputation: 328

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');

Upvotes: 0

Phani Kumar M
Phani Kumar M

Reputation: 4590

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>

Upvotes: 1

alamin
alamin

Reputation: 84

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

Upvotes: 0

anshu purohit
anshu purohit

Reputation: 176

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');

Upvotes: 1

Related Questions