Discuss Ordering fields in the HTML, JavaScript And CSS Help forum on ASP Free. Ordering fields HTML Help forum discussing HTML, DHTML, XHTML, and JavaScript languages for web development, including CSS style sheet coding. All aspects of website development are covered here.
Posts: 41
Time spent in forums: 2 h 34 m 47 sec
Reputation Power: 5
Ordering fields
Anyone know how to order a SELECT field in html in alphabetical order?
I'm too lazy to find the alphabetical positioning of the options, so i just want to sort them.
Posts: 27,640
Time spent in forums: 3 Months 2 Weeks 3 h 4 m 37 sec
Reputation Power: 1902
no built in method, but you can use such code:
Code:
<script type="text/javascript">
function SortCombo(objCombo, ascending, byText)
{
for (var i=0; i<objCombo.options.length; i++)
{
var minMaxIndex=i;
var minMaxValue=(byText)?objCombo.options[i].text:objCombo.options[i].value;
for (var j=i+1; j<objCombo.options.length; j++)
{
var currentIndex=j;
var currentValue=(byText)?objCombo.options[j].text:objCombo.options[j].value;
if (((ascending)&&(currentValue < minMaxValue))||((!ascending)&&(currentValue > minMaxValue)))
{
minMaxIndex = j;
minMaxValue = currentValue;
}
}
if (minMaxIndex != i)
ReplaceComboItems(objCombo, i, minMaxIndex);
}
}
function ReplaceComboItems(objCombo, index1, index2)
{
var strTemp=objCombo.options[index1].text;
objCombo.options[index1].text = objCombo.options[index2].text;
objCombo.options[index2].text = strTemp;
strTemp=objCombo.options[index1].value;
objCombo.options[index1].value = objCombo.options[index2].value;
objCombo.options[index2].value = strTemp;
}
</script>
to activate it, you have to tell it what combo to sort, whether to sort it ascending or not and whether to sort it by the text or value. for example, if you have form called "form1" with combo called "combo1" and you have to sort it by the text (what you actually see) in ascending order, have this in the body tag: