Reputation: 6009
I'm trying to set a variable and upload it to my database depending on what text displays on the page. I am using a simple if...then in javascript, it says that the variable is undefined. Is there another way to set the variable?
<script type="text/javascript">
oldTextAry = new Array();
function changeText (fieldObj, newTexStr) {
if (newTexStr == fieldObj.innerHTML) {
fieldObj.innerHTML = oldTextAry[fieldObj.id];
var waswere = 1;
} else {
oldTextAry[fieldObj.id] = fieldObj.innerHTML;
fieldObj.innerHTML = newTexStr;
var waswere = 2;
}
}
function displayWasWere () {
document.write(waswere);
}
</script>
And the HTML:
<HTML>
<a href="#" onclick="changeText(this,'were');" id="text1link">was</a><br/>
<a href="#" onClick="displayWasWere();" id="waswere" name="waswere">show variable</a>
</HTML>
Upvotes: 0
Views: 1441
Reputation: 3089
Your variable is defined in the scope of the first function. Make the variable global and you should be ready to roll.
Upvotes: 1
Reputation: 15338
make waswere
as global var:
var waswere;
oldTextAry = new Array();
function changeText (fieldObj, newTexStr) {
if (newTexStr == fieldObj.innerHTML) {
fieldObj.innerHTML = oldTextAry[fieldObj.id];
waswere = 1;
} else {
oldTextAry[fieldObj.id] = fieldObj.innerHTML;
fieldObj.innerHTML = newTexStr;
waswere = 2;
}
}
function displayWasWere () {
document.write(waswere);
}
Upvotes: 2