Skip to content
Advertisement

Keyup function is only working once for first letter of input

I have a text input where the user enters a desired page name

<input type='text' id='pageName'  name='PageName' class='form-control pageName'>

I am trying to use the keyup function to fire Ajax to check if the page exists, however when typing something like index Ajax is only sending the I (first letter) and not running again.

Script:

<script>
  $("#pageName").keyup(function() {
    $.ajax({
      type: "GET",
      async: false,
      url: "CheckPageName.php",
      data: {
        'PageName': jQuery(this).val()
      },
      cache: false,
      success: function(html) {
        $("#NotAllowed").replaceWith(html);
        $('#loader_image').hide();
      }
    });
  });
</script>

If I add console.log(html); It shows the values correctly in the log, but $("#NotAllowed").replaceWith(data); is only showing the first letter or 2 (if I type fast!)

What am I missing?

Advertisement

Answer

The issue has nothing to do with your AJAX call (although async:false is still unnecessary and bad practice in general).

The problem is what the jQuery replaceWith function does. As per the documentation it removes the element(s) it matches, and replaces the entire element with the content you supply to the function. Note it replaces the entire element, not just its inner content!

So the reason it only works once is simply because after the first execution, the “NotAllowed” element no longer exists – replaceWith has removed it and replaced it with the response from your AJAX request!

If you want to update the content of an element without removing it, in jQuery you can use .html() or .text() (depending on whether the content is HTML or plain text). In this case .text() would be fine:

success: function(response) {
    $("#NotAllowed").text(response);
    $('#loader_image').hide();
}

Demo: https://jsfiddle.net/k3461n7h/2/

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement