I have a simple select box. When the user chooses an option, an image and a text box containing some code should appear:
<select name="state" id="state" style="margin-bottom: 1em;">
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<!-- etc. etc. -->
</select>
<div id="badgeView"></div>
<div id="codewrap" >
<textarea id="codeView" readonly="readonly"></textarea>
</div>
Here’s the script:
/* Helpful variables */
var codeTemplate = '<a href="http://www.nonprofitvote.org/voting-in-yourstate.html" title="Voting in Your State">\n' + '<img src="http://nonprofitvote.org/images/badges/voting_in_yourstate.jpg" alt="Voting in Your State" />\n' + '</a>';
var state = document.getElementById('state');
var badgeView = document.getElementById('badgeView');
var codeView = document.getElementById('codeView');
/* Load up AL's image and code when the page first loads */
changeBadgeAndCode();
/* What to do when the user selects an option */
state.addEventListener('change', changeBadgeAndCode, false);
/* What to do if a user clicks in the code view text box */
codeView.addEventListener('click', selectText, false);
/* Function declarations */
function changeBadgeAndCode(){
changeBadgeView(badgeView);
changeCodeView(codeView);
var stateName = state.options[state.selectedIndex].value.toLowerCase();
function changeBadgeView(element) {
element.innerHTML = '<img src="http://www.nonprofitvote.org/images/badges/voting_in_' + stateName + '.jpg" />';
}
function changeCodeView(element) {
codeTemplate = codeTemplate.replace(/yourstate/g, stateName);
codeTemplate = codeTemplate.replace(/Your State/g, stateName);
element.innerHTML = codeTemplate;
}
}
function selectText(){this.select()}
If I alert stateName, I get a value that reflects my option choice. But that stateName variable doesn’t seem to make it to the changeBadgeView and changeCodeView functions. I can’t understand why. Any ideas?
You’re invoking
changeBadgeViewandchangeCodeViewbefore thestateNamehas been assigned its value.You need to do the assignment first…