[Last Call] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

Need to change the value of a variable based on a selection box.  (easy)

Posted on 2012-03-29
4
Medium Priority
?
221 Views
Last Modified: 2012-06-28
Hello,

I want to set the value of a variable  outside of the scope of a function.  Does this code accomplish that?  What is a simple way that I can tell?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<script type="text/javascript">
var url="";

function changeUrl(a) {
	if (a.value== "volvo") {
	url = "volvoPage.php"
	alert(url);
	return;
	}
	else { url= "saab.php"
	alert(url)
	return;}
}
</script>
<body>


<select onchange="changeUrl(this)">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
</select>
</body>
</html>

Open in new window

0
Comment
Question by:NewWebDesigner
4 Comments
 
LVL 40

Expert Comment

by:Gurvinder Pal Singh
ID: 37785551
yes, it does. Declaring a variable outside function (or globally) make sure that other methods can also update this variable value
0
 
LVL 35

Expert Comment

by:YZlat
ID: 37786857
looks fine. Are you getting any errors? I am not sure what is your question here
0
 
LVL 20

Accepted Solution

by:
thehagman earned 1000 total points
ID: 37786890
BTW, how yould you have tested this yourself: Add sime other input item that simply calls "alert(url)". You'd have noted that this alrt would always show tha last change made by the select (or "" initially)
0
 
LVL 53

Assisted Solution

by:COBOLdinosaur
COBOLdinosaur earned 1000 total points
ID: 37788971
Your onchange is incorrect the select does not have a value attribute the corrrect syntax is:
onchange="changeUrl(this.options[this.selectedIndex].value;"


Cd&
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Browsers only know CSS so your awesome SASS code needs to be translated into normal CSS. Here I'll try to explain what you should aim for in order to take full advantage of SASS.
This article discusses how to create an extensible mechanism for linked drop downs.
The viewer will learn how to dynamically set the form action using jQuery.
Video by: Mark
This lesson goes over how to construct ordered and unordered lists and how to create hyperlinks.
Suggested Courses

834 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question