Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set the default option for SELECT Tag and how to get the Index of the selected option?

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?

like image 960
TopDeveloper Avatar asked Nov 09 '10 13:11

TopDeveloper


2 Answers

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

like image 119
Šime Vidas Avatar answered Sep 22 '22 23:09

Šime Vidas


<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>
like image 29
ajreal Avatar answered Sep 23 '22 23:09

ajreal