0

I am using jquery for Edit function. This is Working first time after click on submit button. But not working on second time.

$('#btn_editsubmit').click(function() {
  var ans_id = $(this).data('ans_id');
  var name = $(this).data('name');
  var question_id = $(this).data('question_id');
  var e_val = 'editor' + ans_id;
  var d_text = CKEDITOR.instances[e_val].getData();
  // alert(d_text);

  $.ajax({
    type: "post",
    url: '<?= base_url('
    answer ') ?>',
    data: {
      d_text: d_text,
      question_id: question_id,
      ans_id: ans_id
    },
    success: function(result) {
      //alert(result);
      console.log(result);
      myObj = $.parseJSON(result);
      var d = new Date(myObj["added_on"]);
      var day = d.getDate();
      var month = d.getMonth() + 1;
      var year = d.getFullYear();

      if (day < 10) {
        day = "0" + day;
      }

      if (month < 10) {
        month = "0" + month;
      }

      var date = month + " " + day + ", " + year;
      var htm = '<div class="answer" id="answer<?= $answer['
      id '] ?>"><div>' + myObj["answer"] + '</div><div class="blog-content"><span class="post-date">' + date + '</span><a href="#" class="post-author">By ' + name + '</a> <?php if ($answer['
      user_id '] == $this->session->userdata("UserId")) { ?><span><a href="javascript:void(0)" class="btn-edit" data-toggle="collapse" onclick="btn_edit(' + ans_id + ')" data-target="#Edit" data-q_id="<?= $answer['
      id '] ?>">Edit</a></span><div id="Edit" class="collapse"><textarea id="' + e_val + '">' + myObj["answer"] + '</textarea><button id="btn_editsubmit" data-question_id="' + question_id + '" data-ans_id="' + ans_id + '" type="button" class="btn btn-info mt-4">Submit</button></div><?php } ?></div></div>';
      //alert(htm);
      $('#answer' + ans_id).html(htm);
    }
  });
});
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
  • You delete the existing `#btn_editsubmit` and re-create it. This means the original event handler you bound is lost. You need to use a delegated event handler. See the duplicate for more information. Also, be careful that your code doesn't create multiple `id` attributes with the same value, as that is invalid and will cause more problems. – Rory McCrossan Sep 12 '19 at 11:11

1 Answers1

0

This is because jQuery can't bind the click event to dynamically added elements (which is what is happening).

To get around this, use on instead:

$('body').on('click', '#btn_editsubmit', function() {
    ...
});

This will capture the click event on any matching selector #btn_editsubmit underneath body.

Reference the associated documentation.

Martin
  • 16,093
  • 1
  • 29
  • 48