Page is a not externally linkable
- Code, Content, and Presentation
-- JavaScript and AJAX
---- Text change on repeated drop-down lists


Fotiman - 2:45 pm on Mar 9, 2012 (gmt 0)


Welcome to WebmasterWorld!
The problem is that you're using the same id multiple times, which is invalid. An id has to be unique. So start by giving everything a unique id. Then modify your changeText function to take another parameter, your target (instead of hard coding "display").


<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form>
<table>
<tr>
<td>Person 1</td>
<td>Information</td>
<td>
<select id="choice1" onchange="changeText('choice1', 'display1')">
<option>Select</option>
<optgroup label="Category 1">
<option>G1 Choice1</option>
<option>G1 Choice2</option>
</optgroup>
<optgroup label="Category 2">
<option>G2 Choice1</option>
<option>G2 Choice2</option>
</optgroup>
</select>
</td>
<td>
<div id="display1">Select an option</div>
</td>
</tr>
<tr>
<td>Person 2</td>
<td>Information</td>
<td>
<select id="choice2" onchange="changeText('choice2', 'display2')">
<option>Select</option>
<optgroup label="Category 1">
<option>G1 Choice1</option>
<option>G1 Choice2</option>
</optgroup>
<optgroup label="Category 2">
<option>G2 Choice1</option>
<option>G2 Choice2</option>
</optgroup>
</select>
</td>
<td>
<div id="display2">Select an option</div>
</td>
</tr>
</table>
</form>
<script>
var textBlocks = [
'Select an option',
'G1 Choice1 description',
'G1 Choice2 description',
'G2 Choice1 description',
'G2 Choice2 description'
];

function changeText(elemid, displayId) {
var ind = document.getElementById(elemid).selectedIndex;
document.getElementById(displayId).innerHTML = textBlocks[ind];
}
</script>
</body>
</html>

Note, I've moved the script to just before the closing body tag (that's the best place to put scripts). I've removed the type attribute (not needed). And I've cleaned up your array (don't use "new Array", use array literals instead).

Hope that helps.


Thread source:: http://www.webmasterworld.com/javascript/4426936.htm
Brought to you by WebmasterWorld: http://www.webmasterworld.com