Welcome to WebmasterWorld Guest from 54.196.232.162

Forum Moderators: open

Message Too Old, No Replies

Get the value of a select menu

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

Junior Member

5+ Year Member

joined:Mar 14, 2006
posts:58
votes: 0


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

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

Senior Member

WebmasterWorld Senior Member 10+ Year Member

joined:June 18, 2003
posts:1925
votes: 0


var pagesObj = document.getElementById("pages"); 
alert(pagesObj.options[pagesObj.selectedIndex].value);
2:27 pm on July 28, 2006 (gmt 0)

Senior Member from US 

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

joined:Oct 17, 2005
posts:4966
votes: 10


<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]

 

Join The Conversation

Moderators and Top Contributors

Hot Threads This Week

Featured Threads

Free SEO Tools

Hire Expert Members