Aiden
Aiden

Reputation: 460

OPTION element created by document.createElement("option") always has selected attribute as true

I am using javascript and IE11 to implement the code below to add options in a combo box by using javascript

    var bSelected = false;

    for (count of elements to be created)
    {
          **// set value and text and whether to selected the element or not**

          // Create an option and add it to the combo
          opt = document.createElement ("option");
          opt_txt = document.createTextNode (textPart);
          opt.appendChild (opt_txt);
          opt.setAttribute ("value", valuePart);
          opt.setAttribute ("text", textPart);
          opt.setAttribute ("selected", bSelected);
    }

Now even if selected is set to false, opt.selected attribute it always comes out as true. As soon as element is created by createElement function, the default value is true. Please help why it is not changing to false ?

In IE9, it works fine (different HTML version?)

Upvotes: 1

Views: 13897

Answers (1)

Quentin
Quentin

Reputation: 943645

The only allowed value for the selected attribute is "selected" (or "" which means the same thing), but error recovery in browsers means that any value will be treated as if it were "selected".

When you call opt.setAttribute ("selected", bSelected);, the value of bSelected is converted to a string and set to the value.

In this case false is converted to "false" and treated as "selected".

When dealing with boolean attributes, if you don't want them set, then don't set them at all.


Alternatively, you can set the selected DOM property instead of the attribute. The property does take true and false rather than "selected".

opt.selected = bSelected;

Upvotes: 4

Related Questions