Welcome to WebmasterWorld Guest from 54.167.0.111

Forum Moderators: open

Message Too Old, No Replies

Get the value of a select menu

     

evo81

1:27 pm on Jul 28, 2006 (gmt 0)

5+ Year Member



Hello,

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

moltar

1:56 pm on Jul 28, 2006 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



var pagesObj = document.getElementById("pages"); 
alert(pagesObj.options[pagesObj.selectedIndex].value);

Fotiman

2:27 pm on Jul 28, 2006 (gmt 0)

WebmasterWorld Senior Member fotiman is a WebmasterWorld Top Contributor of All Time 5+ Year Member Top Contributors Of The Month



<select id="pages" onChange="updateTotal();">
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>

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]

 

Featured Threads

Hot Threads This Week

Hot Threads This Month