Computing Magazine

Hide HTML Fields with Javascript

Posted on the 29 March 2012 by Akahgy

Description:

Hide or show different HTML fields when markup is changed.

Solution:

There are 3 aspects to take into consideration.

First, we have to identify which element will dictate the change. This is done by adding the property onchange or onclick and so on:

<select id=”age” name=”age” onchange=”javascript: hideFields(document.getElementById(‘age’).value)”>

 

Second, we need to identify which fields will suffer from the change. For this we simply add a distinctive id to them:

<div id=”to_hide”>content of div here</div>

 

Last, we have to create the Javascript function:

function hideFields(age){
   var element_to_hide = document.getElementById(“to_hide”);
   if (age>= 18) {
   element_to_hide.style.display = ”;
   } else {
   element_to_hide.style.display = ‘none’;
   }
}

 

The code above hides an element if age value is less than 18.


Back to Featured Articles on Logo Paperblog