View Full Version : variable scope

11-22-2004, 10:01 PM
I'm trying to setup two functions, one to get a user's choice from a select drop down, and another to send the selected option's text through a separate form to an external PayPal cart.

I thought declaring the main variables outside either function would make them available to both, but I'm doing something wrong...

Here, with the variables in the first function changeIt, this function works as intended, but then selectedDesc is undefined for the second function, addItem. When moving the variables outside the functions, I get an 'object required' error with the first variable.


<script type="text/javascript">
function changeIt()
var selectedColor = document.getElementById('userSelect')
var selectedDesc = selectedColor.options[selectedColor.selectedIndex].text;
var slidePic = document.getElementById('slide')

switch (selectedDesc)
case 'Silver' :
slidePic.src = 'production_images/twist_silver.jpg'

case 'Gold' :
slidePic.src = 'production_images/twist_gold.jpg'

default :
slidePic.src = 'production_images/twist_gold.jpg'

function addItem()
(document.getElementById('payPalItem').value) = selectedDesc;



<img src="production_images/twist_gold.jpg" id="slide">

<form target="paypal" action="https://www.paypal.com/cgi-bin/webscr" method="post" id="payPalForm">
<input type="hidden" name="cmd" value="_cart">
<input type="hidden" name="business" value="">
<input type="hidden" name="item_name" value="" id="payPalItem">
<input type="hidden" name="amount" value="$12.50">
<input type="hidden" name="no_note" value="1">
<input type="hidden" name="currency_code" value="USD">
<input type="hidden" name="lc" value="US">
<input type="hidden" name="item">
<input type="hidden" name="add" value="1">

Choose from:
<select id="userSelect" onchange="changeIt();">
Price Each: $12.50
<a href="#" onclick="addItem();return false;">add to cart</a>


So how do I make the selectedDesc availbale to both functions? Where am I getting this wrong?

11-22-2004, 10:47 PM
By moving the var selectedDesc declaration outside the function. You must still do the assignment selectedDesc = selectedColor.options[selectedColor.selectedIndex].text; inside the function, though.

11-22-2004, 10:59 PM
Thank you. It makes sense now that I can see it working.

EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum