...

View Full Version : variable scope



mcdougals4all
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.



<html>
<head>

<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'
break;

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

default :
slidePic.src = 'production_images/twist_gold.jpg'
break;
}
}

function addItem()
{
(document.getElementById('payPalItem').value) = selectedDesc;
// SEND INFO TO PAYPAL
alert(selectedDesc);
}

</script>

</head>
<body>


<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">
</form>


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



</body>
</html>


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

liorean
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.

mcdougals4all
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