1

I have a web page with a Select option and FORM, When a user changes selection, My jquery script function will dynamically do ajax POST to replace original form with different form (new form elements).

But i noticed that Click handler ($(button).click() Event) is not working on the newly generated form. Please assist on this.

Is this a known problem in Jquery ??.

<select id=choice><option>....</select>
<div class=mytable>
<form id='dataform-10'>
.....
<button id="edit-10"></button>
</form>
<div>
<script>
  $(function(){
  $("#choice").change(function(){
    $.get('/portal/go?id='+this.value, function(data, status){ 
            //$(".mytable").hide();
            $(".mytable").html(data);
            $(".mytable").show();
          });
  });
});
</script>
<script>
$('[id^=edit]').on("click",function(e) {
    e.preventDefault();
   var num = this.id.slice(5);   
   var fdata = $('#dataform-'+num).serialize();
   $.post('/portal/update', fdata, function(data, status){ 
            alert(data);
          });
});
</script>
serverliving.com
  • 437
  • 1
  • 6
  • 16

3 Answers3

1

As has been pointed out by @sh977218 the reason why the click event does not work is the addition of new elements in DOM after the initial tagging of event handlers. Try something like this:

<script>
function clickEventHandler(event) {
  // code for click event 
   event.preventDefault();
   var num = event.target.id.slice(5);   
   var fdata = $('#dataform-'+num).serialize();
   $.post('/portal/update', fdata, function(data, status){ 
        alert(data);
      });
}
$('[id^=edit]').on("click", function(e){clickEventHandler(e);});
$("#choice").change(function(){
  $.get('/portal/go?id='+this.value, function(data, status){ 
        //$(".mytable").hide();
        $(".mytable").html(data);
        $(".mytable").show();
        $('[id^=edit]').on("click", function(e){clickEventHandler(e);});
      });
});
</script>
Arpit Bansal
  • 493
  • 1
  • 4
  • 15
0

When your add some new DOM, you need to hook the event on it again.

Peter Huang
  • 972
  • 4
  • 12
  • 34
0

... $('[id^=edit]').on("click",function(e) { ...

should be

... $(".mytable").on("click", "[id^=edit]", function(e) { ...

Have you tried like this?

Goran Stoyanov
  • 2,311
  • 1
  • 21
  • 31