Very simply, I want to be able to access the year from the select box as an integer. In my test, my alertbox is telling me the value is undefined.
<form name="form1" method="post" action="">
<label>birth year
<select name="birth year" id="dueYear">
<OPTION VALUE='' SELECTED>--Year--</OPTION>
<OPTION VALUE='2011'>2011</OPTION>
<OPTION VALUE='2010'>2010</OPTION>
<OPTION VALUE='2009'>2009</OPTION></SELECT>
</select>
</label>
</form>
<script type="text/javascript">
var dueDateYear = parseInt(document.getElementById("dueYear"));
</script&开发者_高级运维gt;
<button onclick="alert(dueDateYear)">Click Me!</button>
All I want it to do, is tell me the year I have selected -- any help would be appreciated, I am a newbie :(
To get the value of the selected option in plain JS, do as follows:
var dropdown = document.getElementById("elementId");
var optionValue = dropdown.options[dropdown.selectedIndex].value;
See also:
- HTML DOM Select object
That said, your button with the alert won't work well as well. It will display the option as it is during rendering of the page, not the changed options thereafter. Make it a function.
Typically you do this operation in an event, because you care about when it changes.
jQuery
$('#selectionBoxID').change(function(e){
var value = parseInt(e.value.target);
alert(value);
})
Vanilla JavaScript
document.getElementById('selectionBoxID').onchange = function(e){
var value = parseInt(e.value.target);
alert(value);
};
Yes it looks like you are a newbie :-) . document.getElementById() will return you the reference of select select box. Then you need to find out all the options of the select box by doing.
document.getElementById('selectionBoxID').options;
it will give you all the array of all the options object inside it.
Then you can select the selected one using.
document.getElementById('selectionBoxID').options[selectionBox.selectedIndex].value;
note that selectionBox is = document.getElementById('selectionBoxID');
selectionBox.selectedIndex gives you the selected element Index.
do yourself a favor and start using jQuery
alert($('#dueYear').val());
<form name="form1" method="post" action="">
<label>birth year
<select name="birth year" id="dueYear">
<OPTION VALUE='' SELECTED>--Year--</OPTION>
<OPTION VALUE='2011'>2011</OPTION>
<OPTION VALUE='2010'>2010</OPTION>
<OPTION VALUE='2009'>2009</OPTION></SELECT>
</select>
</label>
</form>
<script type="text/javascript">
function alertOptionValue(node_id)
{
var dropdown = document.getElementById(node_id);
var dueDateYear = dropdown.options[dropdown.selectedIndex].value;
alert(dueDateYear);
}
</script>
<button onclick="alertOptionValue('dueYear');">Click Me!</button>
精彩评论