Javascript show hide div, p, input or any HTML elements

We provide hide unhide of an element for providing interactivity to user interface
and sometime for providing input guidelines to user. Sometimes it is also used for
saving space of web page.

You will use this toggle view facility using your choice. You can have select list.
There you can provide number of options to choose from. With those options you can
provide 'other' as option.
Suppose user has selected 'other' as option then you will provide a text box to
enter his option.

Show hide <Div>, <P> elements

Here I have a text link. When a user click on the text link, view of the element will toggle.


<script type="text/javascript">
function toggleview(element1) {
   element1 = document.getElementById(element1);
   if (element1.style.display == 'block' || element1.style.display == '')
      element1.style.display = 'none';
   else
      element1.style.display = 'block';
   return;
}
</script>
<a href="#" onclick="toggleview('div1')">Hide/Unhide DIV</a>
<div id="div1" >
Div will toggle
</div>

Show hide Input element

Here with hiding the text element I am also setting the value to the text element to empty.
So, when your input element is hidden then that input element's value will not be passed to the server on submission.
In this example when an user do not find their city in select list then he is given choice for entering their city in an input element.


<script type="text/javascript">
function toggleElement(sel1, element1) {
  element1 = document.frm1.elements[element1];
  //alert(element1.value);
  if (sel1.value == 'others') {
    element1.style.display = 'inline';
  }
  else {
    element1.value = ''; // input text will be empty
    element1.style.display = 'none'; // hide text element
  }
  return;
}
</script>

<form name="frm1" >
<select name="city" id="city" onchange="toggleElement(this, 'txt1')">
<option value="patna">Patna</option>
<option value="mumbai">Mumbai</option>
<option value="others">Others</option>
</select>
<input type=text name="txt1" id="txt1" value="" /> any text
</form>
<a href="#" onclick="alert(document.frm1.txt1.value)">Check my input value</a>

Knowing the above method you can easily do show-hide with any element like <UL>, <LI>, etc.

Ex. of saving web page's space

  • # 1 - by Satya Prakash Karan

    I do not know how you applied it in blogger. and blogger uses xml syntax, so check correctly for closing tag also.

Comment pages
1 2 220
Comments are open for an year period. Please, write here on Facebook page.