Reputation: 13
I have had many attempts now on attempting to make this work and i dont know what to do i have used the .selectedIndex Method ect. but still no luck, i have made an array of my tags and then sorting them but i would like my "Please select an option" to be the default option. Here's my code :)
function sorting()
{
var mylist = document.getElementById("dropdown");
arritems = new Array();
for(i=0; i<mylist.length; i++)
{
arritems[i] = mylist.options[i].text;
}
arritems.sort();
for(var i=0; i<mylist.length; i++)
{
mylist.options[i].text = arritems[i];
mylist.options[i].value = arritems[i];
}
}
Here is my HTML code:
<form id="form"action = "#">
<label>First Name: </label> <input type="text" id="firstname" /> <br />
<label>Last Name: </label> <input type="text" id="lastname" /> <br />
Please select an option: <select id="dropdown">
<option id="please select" value="Please select an option" selected="selected">Please select an option</option>
<option id="boots" value="Boots" >Boots</option>
<option id="gloves" value="Gloves" >Gloves</option>
<option id="scarf" value="Scarf">Scarf</option>
<option id="hat" value="Hat">Hat</option>
<option id="glasses" value="Glasses">Glasses</option>
</select> <br />
<button id="submits" onclick="table();">Submit</button>
</form>
Upvotes: 1
Views: 290
Reputation: 54649
Try:
// get a handle to thedropdown
var select = document.getElementById('dropdown'), sorted;
if (select) {
// sort an array-copy of the options (exluding the first) by their text value
sorted = Array.prototype.slice.call(select.getElementsByTagName('option'), 1).sort(function (a, b) {
return a.innerText.localeCompare(b.innerText);
});
// flush 'sorted' while re-appending the dom-nodes
while(sorted.length > 0) {
select.appendChild(sorted.shift());
}
}
Upvotes: 1