Ray
Ray

Reputation: 115

Javascript event will not fire up after Ajax call

I have a form (input, textarea and submit button) and I also have a list of items. I wrote the following script to:

  1. when I click a list item the textarea will show the list item text content
  2. on submit, ajax call will POST the form without refreshing the page

the code works fine in the first time but then I will not be able to update the textarea when I click on a list item anymore (point #1 above will not work again).

var ul = document.getElementById('messages-list');

var listItems = Array.prototype.slice.call(ul.querySelectorAll("li"));

listItems.forEach(function (item) {
  item.addEventListener("click", function (event) {
    document.getElementById("message").textContent = this.textContent;
  });
});

$(function () {

  $('form').on('submit', function (e) {

    e.preventDefault();

    $.ajax({
      type: 'post',
      url: 'send_sms.php',
      data: $('form').serialize(),
      success: function () {
        alert('msg sent');
        $('textarea').val("");
        $('#phoneNumber1').val("");
      }
    });

  });

});

Can you please help me fix this issue? Thanks in advance.

Upvotes: 0

Views: 423

Answers (1)

Conan
Conan

Reputation: 2709

Try updating your forEach to use .val() when updating the textarea:

listItems.forEach(function (item) {
  item.addEventListener("click", function (event) {
    $('#message').val(this.textContent);
  });
});

As stated by others, .val() is the preferred method of getting / setting content - mixing this with textContent appears to cause the issue you're experiencing.

Upvotes: 1

Related Questions