Allow to open only one div

1

Code to call the divs:

<input style="float: right;" class="botao1" onclick="addRisco()" value="Adicionar Risco"/>
  </td>
     </tr>
 </table>
        </fieldset>
<div id="riscos">

</div>
<fieldset class="grupo">
    <table width="100%" class="campo" cellspacing="10">
        <tr>
        <td>
 <input style="float: right;" class="botao1" onclick="addRisco1()" value="Acção"/>
  </td>
     </tr>
 </table>
<div id="riscos1">

</div>

With this function whenever I click the button it opens a div:

function addRisco(){ 
$("#riscos").append("<div>"+$("#riscoform").html()+"</div>"); 
} 
function addRisco1(){ 
$("#riscos1").append("<div>"+$("#riscoform1").html()+"</div>"); 
} 

But I want the function to only allow the div to open once.

    
asked by anonymous 10.08.2018 / 16:10

2 answers

5

When you use the one() method, the function is executed only once for each element.

  

put an id for each element

$("#botao").one("click", function(){
    $("#riscos").append("<div>"+$("#riscoform").html()+"</div>"); 
}); 

$("#botao1").one("click", function(){
    $("#riscos1").append("<div>"+$("#riscoform1").html()+"</div>"); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><inputid="botao" style="float: right;" class="botao1" value="Adicionar Risco"/>
  </td>
     </tr>
 </table>
        </fieldset>
<div id="riscos">

</div>
<fieldset class="grupo">
    <table width="100%" class="campo" cellspacing="10">
        <tr>
        <td>
 <input id="botao1" style="float: right;" class="botao1" value="Acção"/>
  </td>
     </tr>
 </table>
<div id="riscos1">

</div>
  

With the function one() it is not necessary to check if tem Filhos ie descending elements of the selected element

$("#botao").one("click", function(){
    $("#riscos").append("<div>"+$("#riscoform").html()+"</div>"); 
}); 

$("#botao1").one("click", function(){
    $("#riscos1").append("<div>"+$("#riscoform1").html()+"</div>"); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><fieldsetclass="grupo">
<input  id="botao" style="float: right;" class="botao1" value="Adicionar Risco"/>

<div id="riscos"></div>

<br><br>
 <input id="botao1" style="float: right;" class="botao1" value="Acção"/>

<div id="riscos1"></div>

.one ()

    
10.08.2018 / 16:32
1

Try this:

function addRisco(){
    var temFilhos = $("#riscos").find("div").length > 0;

    if(!temFilhos){
        $("#riscos").append("<div>"+$("#riscoform").html()+"</div>"); 
    }
} 

function addRisco1(){ 
    var temFilhos = $("#riscos1").find("div").length > 0;

    if(!temFilhos){
        $("#riscos1").append("<div>"+$("#riscoform1").html()+"</div>"); 
    }
} 

Tip: Start customizing your code, even when writing test codes, it will naturally do so. It helps a lot to visualize the html hierarchy, and makes it very easy to maintain.

    
10.08.2018 / 16:22