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).
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.
var select = $("<select></select>"); var opt = $("<option></option"); opt. val("1"); opt. html("Option 1"); select.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With