SHow/hide elements based on selected option

Hello there,
I’ve tried to find a stright forward script which show/hide specific form fields based on a selected option. I’ve seen many online but non of them was working with me without the need of some coding or tweeks. Does anyone here have such script?

Any help would be highly appreciated in advance,
Regards,

1 Like

basically, what you need is

  1. an onclick or some aother event handler on an element.

  2. when that event in 1) occurs, call a function that changes the display styles on other elements from none to block and/or vice versa

If you post the code you have so far we can try to help you debug it if you are stuck.

1 Like

Thank you for your quick repsonse.
I’m trying to implement this code in this link:
http://stackoverflow.com/questions/835259

Actually, I’m stuck with how to implement the jquery code and I’m not sure if it conflicts with prototype script too or not.!!

1 Like

I’m not sure how to do it in jquery, but to me it’s a lot simpler in plain vanilla javascript.

Try something like this

 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<style type="text/css">
 
#div1,#div2,#div3 {
display: none
}
 
</style>
<script type="text/javascript">
 
function showHide(elem) {
    if(elem.selectedIndex != 0) {
         //hide the divs
         for(var i=0; i < divsO.length; i++) {
             divsO[i].style.display = 'none';
        }
        //unhide the selected div
        document.getElementById('div'+elem.value).style.display = 'block';
    }
}
 
window.onload=function() {
    //get the divs to show/hide
    divsO = document.getElementById("frmMyform").getElementsByTagName('div');
}
</script>
</head>
<body>
 
<form action="#" method="post" id="frmMyform">
 
 <select name="selMyList" onchange="showHide(this)">
        <option value="">Select an option</option>
        <option value="1">Show div 1</option>
        <option value="2">Show div 2</option>
        <option value="3">Show div 3</option>
 </select>
 
 <div id="div1">This is Div 1</div>
 <div id="div2">This is Div 2</div>
 <div id="div3">This is Div 3</div>
 
</form>
 
</body>
</html>

Simple straight forward, thanks :wink:

1 Like