Connecting Tech Pros Worldwide Forums | Help | Site Map

Getting the selected value of a select input

Newbie
 
Join Date: Nov 2007
Posts: 7
#1: Mar 31 '09
All,

I'm having a little trouble getting the value of a select in my html form. I want a list of dates in a dropdown and when the user clicks on refresh it should do the appropriate action. But when I run in IE7, it comes up with the selectedIndex being undefined.

In my HTML body, I have the select and standard button:

Expand|Select|Wrap|Line Numbers
  1. <body id="example" onload="displayXML();">
  2.     <div class="divPageHeader" style="width: 100%;">
  3.         <select id="dateSelect">
  4.                         <option value="1-Dec-2000">1-Dec-2000</option>
  5.                         <option value="1-Dec-2010">1-Dec-2010</option>
  6.                     </select>
  7.                     <input id="refresh" type="button" value="Refresh" onclick="fnDateChange();" />
  8.     </div>
  9. </body>
  10.  
And in the head, I have the function defined...

Expand|Select|Wrap|Line Numbers
  1. <head>
  2.         <script language="javascript" type="text/javascript">
  3.  
  4.             function fnDateChange() 
  5.             {
  6.                  var selectedDate = document.getElementById("dateSelect").value
  7.                  alert(selectedDate.toString());
  8.                  alert("Index = " + selectedDate.selectedIndex);
  9.                  var oStartDT = selectedDate.options[selectedDate.selectedIndex].value;
  10.  
  11.             }
  12.         }
  13.  
  14.  
  15.     </script>
  16.  
When I run the form, I select the date and click on refresh. And it comes up wit the:

Message box alert with 1-Dec-2010
Message box alert with Index = undefined
Script error

Error: 'options' is null or not an object.
Code: 0

acoder's Avatar
Site Moderator
 
Join Date: Nov 2006
Location: UK
Posts: 14,581
#2: Mar 31 '09

re: Getting the selected value of a select input


selectedDate should be the select object, not the value, so change line 6 to:
Expand|Select|Wrap|Line Numbers
  1. var selectedDate = document.getElementById("dateSelect");
Newbie
 
Join Date: Nov 2007
Posts: 7
#3: Mar 31 '09

re: Getting the selected value of a select input


Yep. Ya beat me to posting the reply cheers...
acoder's Avatar
Site Moderator
 
Join Date: Nov 2006
Location: UK
Posts: 14,581
#4: Mar 31 '09

re: Getting the selected value of a select input


Some very old browsers may not accept it, but you could change line 9 to:
Expand|Select|Wrap|Line Numbers
  1. var oStartDT = selectedDate.value;
Will work in probably all modern browsers.
Reply

Tags
html, null, problem, select, selectedindex