I would like to have a code in HTML and JavaScript that process SELECT and OPTION Elements
<select>
<option>
</option>
<option>
</option>
</select>
How I can get the Index of the selected option and then get the value of this index?
How can I make 2010 as the default option visual for users in the select tag existing in the form in a web page?
My code looks like that :
<select id="SelectYear" name="SelectYear" size="1">
<script type="text/javascript">
var startyear = "1950";
var endyear = "2020";
for(var k=startyear; k<=endyear; k++ ) document.write("<option value="+k+">"+k+"</option>");
</script>
</select>
I tried many expressions to get that index even I know it may give a different thing like:
var vIndex = document.getElementById('SelectYear').selectedIndex;
var vIndex = document.getElementById('SelectYear').selectedIndex.value;
var vIndex = document.getElementById('SelectYear').selectedIndex.text;
var vIndex = document.getElementById('SelectYear').options[document.getElementById('SelectYear').selectedIndex];
var vIndex = document.getElementById('SelectYear').options[document.getElementById('SelectYear').selectedIndex].value;
var vIndex = document.getElementById('SelectYear').options[document.getElementById('SelectYear').selectedIndex].text;
My workaround solution is to put the index static like:
document.getElementById('SelectYear').selectedIndex = 60 ;
But if I do not know the exact index or the index is changed according to the changes happended in the SELECT elements due to database update or manual edit?
To set the default option based on the index, try this:
select_element.options[the_index].defaultSelected = true;
(You may also have to set this property to false to the previous default option.)
Source: DOM 2 HTML spec: http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-37770574
<select id="SelectYear" name="SelectYear" size="1">
<script type="text/javascript">
var startyear = "1950";
var endyear = "2020";
for(var k=startyear; k<=endyear; k++ )
{
var selected = (k==2010) ? 'selected' : '';
document.write("<option value='"+k+"'"+selected+">"+k+"</option>");
}
</script>
</select>
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