0

Here i am creating dynamic radio buttons, text area and click events but my click events for add and remove button is not working for the dynamically created button. I tried using on click event of jquery but it is not working as expecte. How to add .on jquery function in my scenario i tried using :

$("#TextBoxesGroup")‌​.on("click", ".abc", (function () {
 //some script
});

but when i click on the new dynamic add button which i created it is not at all adding another block

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).ready(function(){
var counter = 2;
alert(123);
$(".abc").click(function () {
if(counter>10){
        alert("Only 10 textboxes allow");
        return false;
}

 var newTextBoxDiv = $(document.createElement('div'))
  .attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Textbox #'+ counter + ' : </label>' +
   '<input type="text" name="textbox' + counter +
   '" id="textbox' + counter + '" value="" ><br><input type="radio" name="gender' + counter + ' value="male" > Male<input type="radio" name="gender' + counter + ' value="male" > Female<br><textarea  id="textbox' + counter + ' rows="4" cols="50"></textarea><input type="button" class="abc" id="addButton' + counter + '" value="Add Button" ><input type="button" id="removeButton' + counter + '" value="Remove Button" >');

 newTextBoxDiv.appendTo("#TextBoxesGroup");


 counter++;
 });
$("#removeButton").click(function () {
 if(counter==1){
      alert("No more textbox to remove");
      return false;
   }

 counter--;
$("#TextBoxDiv" + counter).remove();
});
$("#getButtonValue").click(function () {

var msg = '';
for(i=1; i<counter; i++){
  msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
</script>
</head>
<body>

</head>
<body>

<div id='TextBoxesGroup'>
 <div id="TextBoxDiv1">
  <label>Textbox #1 : </label><input type='textbox' id='textbox1' >
   <input type="radio" name="gender" value="male"> Male
   <input type="radio" name="gender" value="female"> Female<br>
   <textarea id="textbox" rows="4" cols="50"></textarea>
    <input type='button' class="abc" value='Add Button' id='addButton'>
    <input type='button' value='Remove Button' id='removeButton'>
    <input type='button' value='Get TextBox Value' id='getButtonValue'>
</div>

1 Answers1

-1

Use event delegation.

$(".abc").on('click',function(){

    //add your script
})

OR

$("immediate_parent_id_or_class").on('click',".abc",function(){

        //add your script
})
RIYAJ KHAN
  • 15,032
  • 5
  • 31
  • 53