March 19, 201016 yr Hi, I am having a little problem with a form i am trying to create. What i need it to do is when Company is selected it hides the freelance div and shows the company div and vice versa. Here is what i have so far. Javascript function displayElements(number) { switch(number) { case 1: document.getElementById("company").setAttribute("style", "visibility:visible"); break; case 2: document.getElementById("freelance").setAttribute("style", "visibility:hidden"); break; } } HTML <select name="customerType" onclick="displayElements(this.value);"> <option value="0">Type?</option> <option value="1">Freelancer</option> <option value="2" >Company</option> </select> <div id="freelance" style="visibility:visible"> Forename <input type="text" name="forename" id="forename" /> Surname <input type="text" name="surname" id="surname" /> </div> <div id="company" style="visibility:hidden"> Company Name <input type="text" name="companyName" id="companyName" /> </div>
March 19, 201016 yr Hi Thomas, I'm just typing this in the editor so forgive me if there are any typos Just before the </body> of your page put the following: <style type="text/css"> .hidden {visibility:hidden;} .visible {visibility:visible;} </style> <script type="text/javascript"> window.onload = function () { var dropDown = document.getElementById('customerType'); document.getElementById('company').className = 'hidden'; dropDown.onchange = function () { displayElements(this.options[this.selectedIndex].value); } } function displayElements(index) { switch(index){ case '1': document.getElementById("company").className = "hidden"; document.getElementById("freelance").className = "visible"; break; case '2': document.getElementById("freelance").className = "hidden"; document.getElementById("company").className = "visible"; break; } } </script> and your html would look like this: <select id="customerType" id="customerType"> <option value="0">Type?</option> <option value="1">Freelancer</option> <option value="2" >Company</option> </select> <div id="freelance"> Forename <input type="text" name="forename" id="forename" /> Surname <input type="text" name="surname" id="surname" /> </div> <div id="company"> Company Name <input type="text" name="companyName" id="companyName" /> </div> This way you keep the javascript separate from your html. Also notice, I've changed the class names of the divs to show/hide them instead of directly accessing the style property. That keeps your js separate from your css Anyway, it's not tested but should do the job
March 20, 201016 yr Author Thanks a lot ElanMan. That works fine, just out of interest was it possible to do it the way i was trying to with the onclick or onchange?
Create an account or sign in to comment