Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create HTML select option using properties or attributes

I want to programmatically create a selected HTML select option using Javascript (not jQuery). What are the merits of creating it by setting the attributes as follows:

var option = document.createElement('option');
option.setAttribute('text', 'option1');
option.setAttribute('value', 5);
option.setAttribute("selected", true);

as opposed to setting properties:

var option = document.createElement('option');
option.text = 'option1';
option.value = 5;
option.selected = true;

I'd prefer to create the options using properties but just want to be sure that this isn't going to cause any issues, as many of the examples I've come across on the web tend to favour using the former approach (i.e. setting attributes).

like image 684
aw1975 Avatar asked Sep 24 '15 15:09

aw1975


People also ask

How do you select attributes in HTML?

The <select> element is most often used in a form, to collect user input. The name attribute is needed to reference the form data after the form is submitted (if you omit the name attribute, no data from the drop-down list will be submitted). The id attribute is needed to associate the drop-down list with a label.

How do I create a dynamic selection in HTML?

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

What is Option attribute in HTML?

The <option> tag defines an option in a select list. <option> elements go inside a <select>, <optgroup>, or <datalist> element. Note: The <option> tag can be used without any attributes, but you usually need the value attribute, which indicates what is sent to the server on form submission.


1 Answers

setAttribute should be used on DOM elements and lowercases the attribute name on HTML elements. You can't use dot notation to assign values to dynamic attribute names.

Using setAttribute() to modify certain attributes, most notably value in XUL, works inconsistently, as the attribute specifies the default value. To access or modify the current values, you should use the properties. For example, use elt.value instead of elt.setAttribute('value', val).

So in summary, use setAttribute if you have dynamic attribute names. If you have normal attributes, use dot notation.

like image 99
Richard Hamilton Avatar answered Oct 06 '22 01:10

Richard Hamilton