homepage Welcome to WebmasterWorld Guest from 54.226.21.57
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
Forum Library, Charter, Moderator: open

JavaScript and AJAX Forum

    
Get the value of a select menu
evo81

5+ Year Member



 
Msg#: 3025758 posted 1:27 pm on Jul 28, 2006 (gmt 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

 

moltar

WebmasterWorld Senior Member 10+ Year Member



 
Msg#: 3025758 posted 1:56 pm on Jul 28, 2006 (gmt 0)

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

Fotiman

WebmasterWorld Senior Member fotiman us a WebmasterWorld Top Contributor of All Time 5+ Year Member



 
Msg#: 3025758 posted 2:27 pm on Jul 28, 2006 (gmt 0)

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

Global Options:
 top home search open messages active posts  
 

Home / Forums Index / Code, Content, and Presentation / JavaScript and AJAX
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved