Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hide/show advanced option using JavaScript

I'm making an HTML form, and I'd like some fields to be under "Advanced Options". I want to make an "Advanced Options" link, maybe with a "plus" sign, so that when the user clicks on the link or the sign, those advanced fields show up. How can I do this in JavaScript? I've tried searching for something like "Hide/show advanced option" on Google, but can't find a solution.

<form ... />
    <label>
      Title 
      <input id="title" name="title" size="40" type="text" value="" /> 
    </label>
    <label>
      Year 
      <input id="year" name="year" size="20" type="text" value="" /> 
    </label>
    <label>
      Year 
      <input id="comment" name="comment" size="40" type="text" value="" /> 
    </label>
</form>

For example, here I want the "comment" field to be advanced.

like image 816
Mika H. Avatar asked May 27 '13 19:05

Mika H.


2 Answers

<a href='#' class='advanced'>Advanced Options</a>

<div id='advancedOptions'><!-- Form stuff here --></div>

<script type='text/javascript'>
    $(document).ready(function () {
        $('#advancedOptions').hide();
        $('.advanced').click(function() {
            if ($('#advancedOptions').is(':hidden')) {
                 $('#advancedOptions').slideDown();
            } else {
                 $('#advancedOptions').slideUp();
            }
        });
    });
</script>

It will hide the advancedOptions element on load, when you click the a tag it will check if the advancedOptions is hidden, if it is then it will show it if it isn't hidden it will hide it. You will need;

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script> 

at the top of the page you're using, I know it's JQuery, but it would be useful to learn JQuery for future reference

like image 165
user2406160 Avatar answered Oct 03 '22 12:10

user2406160


You're looking for something like this (Pure JS):

function more(obj) {
    var content = document.getElementById("showMore");

    if (content.style.display == "none") {
        content.style.display = "";
        obj.innerHTML = "-";
    } else {
        content.style.display = "none";
        obj.innerHTML = "+";
    }
}

This function checks the visibility of your content, if it's hidden, shows it, and vice versa. It also changes the plus sign to a minus. Here's the revised HTML:

<a href="#" onclick="more(this);">+</a>
<br>
<label id="showMore" style="display: none;">
  Year 
  <input id="comment" name="comment" size="40" type="text" value="" /> 
</label>

And a demo: http://jsfiddle.net/uSqcg/

like image 24
tymeJV Avatar answered Oct 03 '22 12:10

tymeJV