Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Set selected attribute on DOM created select options 1

Status
Not open for further replies.

theniteowl

Programmer
May 24, 2005
1,975
US
I am rebuilding a select box using the DOM add() method.
Any way to set the selected attribute through this method so I do not have to loop through the whole set later comparing values in order to set selected correctly?

At my age I still learn something new every day, but I forget two others.
 
Never mind, found it.

myobj.setAttribute('selected', true);


At my age I still learn something new every day, but I forget two others.
 
niteowl, to answer your original question:

Using the add method you cannot set an item to selected, you will have to use a secondary method as you showed above in your 2nd thread. Here's the w3c's definition of the add method:


As you can see the constructor method only accepts 2 values, and neither of them define the "selected" status.

However, if you use the Option object, you can set a new option initially to "selected". Here's a reference to the Option object and a detailed explanation of it's constructor:


-kaht

[small](All puppies have now found loving homes, thanks for all who showed interest)[/small]
 
Thanks Kaht, that will be useful in the future.

I actually got around the problem in this case by testing the previously selected text value against the new text values as they are being created and kept track of the new index number so at the end of the function I could set the appropriate selectedIndex against the already created options.

I did it this way for other reasons based on how I assigned the value and text properties and filtered which options to display. Which options would show is dependent on values in the database but also upon an external value I had to test against.

It's one of those situations where the solution is very simple to look at but took a log of thinking and testing to come up with. :)

This situation is unusual though and in the future I will make use of what you showed above.

At my age I still learn something new every day, but I forget two others.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top