August 23, 2005
Select Fields & Div TagsSimplified
A co-worker was having problems getting a JavaScript to work, attempting to reveal a given hidden div tag based on a select field form selection. He was going about it in a more complicated manner, and I stepped in and offered a much more simplified approach to revealing a div tag based on a form selection.
First, the source code:
<script language="javascript">
<!–
function showField(hiddenField) {
var swapWithThis = document.getElementById(hiddenField).innerHTML;
document.getElementById(”targetField”).innerHTML = swapWithThis;
}
//–>
</script>
<form action=”">
<select id=”selectField” onChange=”showField(this.value);”>
<option value=”">select an option</option>
<option value=”divOne”>Show div one</option>
<option value=”divTwo”>Show div two</option>
<option value=”divThree”>Show div three</option>
</select>
</form>
<div id=”targetField”></div>
<div id=”divOne” style=”display: none;”>This is Div 1</div>
<div id=”divTwo” style=”display: none;”>This is Div 2</div>
<div id=”divThree” style=”display: none;”>This is Div 3</div>
In this example, we’ve got some hidden div tags with content and a select field with values that correspond with the given hidden div tags. We’re simply running a function I created called “showField” with every onChange event that occurs with that form field. On that event, we’re sending the value (this.value) of the selection field “selectField” to the function. The function then grabs the innerHTML (all that is contained within the DIV tag—HTML included) of the corresponding div tag—that is, the div tag that has an ID value that matches the selection value.
We then take that innerHTML and slap it into the blank target div tag (id=”targetField”). It’s really simple, actually, and works like a charm. Test the demo here.
Parting Thought…
If you’re using this method to reveal more select fields or modify values in other target form fields, it would be wise to make use of a target HIDDEN form field to capture the final data value that you’re after. Why? Depending upon how you’re using this, you might run the risk of losing your form data/attributes in those hidden/revealed states. What I suggest is having hidden form elements to receive the final selection values—this way they remain unaffected by the selection event.
UPDATE 4/19/2006: When I originally posted this entry, I had “visiblity: none;” as the attribute in the DIV tags. The PROPER attribute is to have “display: none;” instead. This will ensure that nothing in that layer displays whatsoever.

August 23, 2005, 2:25 pm
Filed under: HTML, JavaScript
Leave a Comment
You must be logged in to post a comment.

