Forum Moderators: open
Ive just started learning ajax and need some help writing my first little bit of script...
I want to get the value of a select menu
<select id="pages" onChange="updateTotal();">
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
Can i just use
var pages = document.getElementById("pages").value
?
Any help much appreciated
Here's a better way (note, replace ¦¦ with two pipe characters):
function updateTotal()
{
// Validate that the browser knows getElementById
if(!document.getElementById ) return;
// Get the "pages" select box
var pagesObj = document.getElementById("pages");
// Validate that the object exists
if(!pagesObj ) return;
// Get the options array. This works for both
// single select and multi select boxes
if( typeof(pagesObj.options) == "undefined" ¦¦ pagesObj.options == null ) return;
var o = pagesObj.options;
// Get the selected options into an array
var s = new Array();
for( var i = 0; i < o.length; i++ )
{
if( o[i].selected )
{
s[s.length] = o[i].value;
}
}
// s now contains an array of the selected values.
// If nothing was selected, the array length is 0
if( s.length == 0 )
{
alert("You must select a value.");
}
else
{
for( var i = 0; i < s.length; i++ )
{
// Do whatever you want with the values here
alert("You selected: " + s[i];
}
}
}
[edited by: Fotiman at 2:31 pm (utc) on July 28, 2006]