Javascript-CSS Show and Hide form elements

user599531 picture user599531 · May 3, 2011 · Viewed 29.1k times · Source

By using Javascript how to show and hide some parts of the table(Eg: TR or TD). This should work depending on the data fetched from the Database I am using CakePHP framework for my Application and using a single view file for Add and Edit. In Edit mode - Depending on the data fetched, I need to show and hide some parts of the form elements.

Scenario There are five questions A,B,C,D nad E B is dependent on A, C is dependent on B, D is dependent on C and E is dependent on D So while adding I have hidden B,C,D and E on selecting of the respective questions the other questions will be displayed. A,B,C,D - All are "Yes/No"(radio buttons) questions.

Eg:

<'table>
<'tr id='a'>
  <'td colspan='2'>A<'/td>
<'/tr>  
<'tr id='b'>
  <'td colspan='2'>B<'/td>
<'/tr>
<'tr id='cd'>
  <'td id='c'>C<'/td><'td id='d'>D<'/td>
<'/tr>
<'/table>

(' Prefix for all HTML tags)

How can I do it. Please post your comments.

Answer

Richard picture Richard · May 3, 2011

CSS has two special attributes, the first one is display and the second is visibility.

display

Has many properties or values, but the ones we need are none and block. none is like a hide value, and block is like show. If you use the none value you will totally hide what ever HTML tag you have applied this CSS style. If you use block you will see the HTML tag and its content.

visibility

Has many values, but we want to know more about the hidden and visible values. hidden will work in the same way as the block value for display, but this will hide tag and its content, but it will not hide the physical space of that tag.

For example, if you have a couple of text lines, then and image (picture) and then a table with three columns and two rows with icons and text. Now if you apply the visibility CSS with the hidden value to the image, the image will disappear but the space the image was using will remain in its place. In other words, you will end with a big space (hole) between the text and the table. Now if you use the visible value your target tag and its elements will be visible again.

Then you can change them via JavaScript for display:

document.getElementById(id).style.display = "none";
document.getElementById(id).style.display = "block";

for visibility:

document.getElementById(id).style.visibility= "hidden";
document.getElementById(id).style.visibility= "visible";

So you can create a function that does this, and then reference that function when they select the correct answer. It depends how they select it to how you would make it show.

Otherwise if this isn't what you want the innerHTML function could also work.