-2

I have a button on my document, upon clicking will generate certain html tags.

<a type="button" name="repbut" >Reply</a> //on button click

    <script type="text/javascript"> // this script will be executed
    $(document).ready(function(){
    $('a[name=repbut]').click(function(){
        var boxid=$(this).attr("id");   
        $("#"+boxid+"1").html('<ul><li><div class="comment"><div class="comment-content"><div class="comment-meta-author">Post your reply</div><br><div class="comment-body"><div class="form-group"><label>Message</label><textarea id="reep" class="form-control" rows="2"></textarea><br><span id="'+boxid+'2"></span><a type="button" name="repcom" id="test" value="'+boxid+'" class="btn btn-primary pull-right">Reply</a></div><br></div></div></div></li></ul>');
    });
    });
    </script>

The problem is when i click the generated button nothing happens, not even alert function.

<a type="button" name="repcom" id="test" class="btn btn-primary pull-right">

<script type="text/javascript">
$('a[name=repcom]').click(function(){
        alert("yes"); // not triggered
        });
</script>

Am i doing something wrong? i am new to jQuery. Any help is appreciated.

SALT
  • 3
  • 3

3 Answers3

0

jQuery's .click() will not work on dynamically generated html.

Use .on() instead.

$( "body" ).on( "click", "a[name=repcom]", function() {
  console.log("This Works");
});
Prabhu Vinod
  • 168
  • 9
0
$('#test').on("click", function(){
    alert("yes"); 
});
Amol B Lande
  • 214
  • 1
  • 2
  • 13
0

 $(document).ready(function(){
    $('a[name=repbut]').click(function(){
        var boxid=$(this).attr("id");   
        $("#newhtml").html('<ul><li><div class="comment"><div class="comment-content"><div class="comment-meta-author">Post your reply</div><br><div class="comment-body"><div class="form-group"><label>Message</label><textarea id="reep" class="form-control" rows="2"></textarea><br><span id="'+boxid+'2"></span><a type="button" name="repcom" id="test" value="'+boxid+'" class="btn btn-primary pull-right">Reply</a></div><br></div></div></div></li></ul>');
    });
    
     $(document).on('click','a[name=repcom]',function(){
     alert("yes =" +  $("#reep").val())
     })
        
    });
    
    
  
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a type="button" name="repbut" >Reply</a>
<div id='newhtml'> </div>
Karan Singh
  • 806
  • 1
  • 6
  • 12