Search code examples
javascriptjqueryonclickouterhtml

Onclick event issue after using the outerHTML


this is the code :

$(".adauga_incasare").click(function(){
       var html = $(".incasari")[0].outerHTML;
       $(html).insertAfter($(".incasari").last());
    });

    $(".del_incasare").click(function(){
         alert("dsdasdasd");
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
    			<div class="incasari">
    				<div class="data_incasare_container">
    					<label><b>Data</b></label>
    					<input class ="data_incasare" type="text" id="datepicker">
    					<label class ="data_incasare_hidden">12-06-2014</label>
    				</div>
    				<div class="suma_incasare_container" style="">
    					<label><b>Suma</b></label>
    					<input class="suma_incasare" type="text" maxlength="8" name="pret_unitar[]" alt=""> 
    					<label class ="suma_incasare_hidden">100</label>
    				</div>
    			    <div class="coscos" style="">
    			   	     <a class="stergereIncasare" href="javascript:void(0);"><i class="icon-trash"></i></a>
    			   	     <div style="clear:both;"></div>	
    			   	     <div class ="incasare_action">
    				   	     <input class="btn btn-success" type="button" style="margin-left:50px;width:80px;height:30px;float:left;" value="Salveaza"></input>
    				   	     <a href="javascript:void(0);" class="del_incasare delrow"></a>
    			   	 	 </div>
    			   	 	 <div style="clear:both;"></div>
    			    </div>
    			    <div style="clear:both;"></div>
    		    </div>
    
    		    <div style="clear:both;"></div>	
    			<a href="#" class="adauga_incasare">+ Adauga incasare noua</a>
    			<div class="toram">
    					<label style = 'cursor:default;'>Total incasat: <b>100 &euro;</b></label>
    					<label style = 'cursor:default;'>Total ramas: <b>1012 &euro;</b></label>
    			</div>		
    		</div>

the outerHTML works fine, but when i "clone" the class incasari after that , when the onclick event doesnt work on the clone part. I have a delete button. In the first class "incasari" in works , but in the clone class it does not . Why ?


Solution

  • Use Event Delegation because your element is dynamically created after the click event was assigned. For example, to delegate to the document:

    Demo

    $(document).on("click", ".del_incasare", function(){
        alert("dsdasdasd");
    });
    

    This means all clicks will be checked by the .del_incasare selector, and if it matches then the function will run, regardless of when the element was created.