Search code examples
javascriptjquerycssgrailsgsp

hide various buttons with different div Javascript within a form


this is my code

press to hide , then press to display

<script type="text/javascript">
    var clic = 1;
    function hideFecha(){
        if (clic == 1){
            document.getElementById('fecha').style.display='none';
            clic = clic + 1;
        } else {
            document.getElementById('fecha').style.display = 'block';      
            clic = 1;
        }   
    }
</script>

//press to hide , then press to display

<script type="text/javascript">
    var click = 1;
    function hidePerson(){
        if (click == 1){
            document.getElementById('person').style.display='none';
            click = click + 1;}
        else{
            document.getElementById('person').style.display = 'block';      
            click = 1;
        }   
    }
</script>

my form

<g:form  controller="SoliCon" action="save" >
    <fieldset id="solContri" class="form">
        <div>
            <fieldset id="solContri" class="buttons">
                <center><input type="button" name="fecha" value="FECHA" onclick="hideFecha()"/></center>
            </fieldset>  
            <div id="fecha" >     
                <g:render  template="formfecha"/>
                <br>
            </div>
        </div>

Stylish button hides the div

        <div>
            <fieldset id="solContri" class="buttons">
                <input type="button" name="person"     value="PERSON"             onclick="hidePerson()"/>
            </fieldset>
            <div id="person">
                <g:render template="persona"/>
            </div>
        </div>
    </div>
</fieldset>
</g:form>

Press to hide then press to display The catch is that when there are two or more templates javascript code does not work.

ERROR hidePerson is not defined , ERROR: hideFecha is not defined


Solution

  • You have a couple issues with your code.

    1.) You have multiple elements with the same id ( solContri )

    2.) You have an extra closing div tag

    The errors you were receiving were due to the duplicate ID.

    See the code below. I believe it is what you are after.

    $("#solContri-person").click(function(){
    	$("#person").hide();
    });
    
    $("#solContri-fecha").click(function(){
    	$("#fecha").hide();
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
    <fieldset id="solContri" class="form">
      <div>
        <fieldset id="solContri-fecha" class="buttons">
          <center><input type="button" name="fecha" value="FECHA" /></center>
        </fieldset>  
        <div id="fecha" >     
          <br>
        </div>
      </div>
      <div>
        <fieldset id="solContri-person" class="buttons">
          <input type="button" name="person"     value="PERSON" />
        </fieldset>
        <div id="person">
    <br/>
        </div>
      </div>
    </fieldset>