Steve Woods
Steve Woods

Reputation: 227

JQuery load() function keeps clearing user input

I've got JQuery with a load() function that works every second. However, when I type user input into a search box, it won't work.

$(document).ready(function() {
function loadData() {
$('body').load('index.php', function() {
  if(window.reloadData != 0)
    window.clearTimeout(window.reloadData);
    window.reloadData = window.setTimeout(loadData, 1500)
}).fadeIn("slow");
}

window.reloadData = 0;
loadData();

});

<form action="search.php" method="get"><input type="text" placeholder="Search for movie"></form>

Upvotes: 0

Views: 40

Answers (1)

Lucas
Lucas

Reputation: 1311

If you really wan't to replace the entire body and save the form state, just remove the form and put it back:

<!--Index.php-->
<!-- Set a identifier for it -->
<form id="searchForm" <!--more attributes...--> ></form>

The Script :

///main.js

(($) => {
   const loadData = () => {
      //"take" the form 
      let $form = $('#searchForm').detach();

      $('body').load('index.php', () => {

          if(window.reloadData != 0)
             window.clearTimeout(window.reloadData);

          window.reloadData = window.setTimeout(loadData, 1500);

          //replace the default form with the saved form
          $('#searchForm').replaceWith($form);

        }).fadeIn("slow");
      }
   $(document).ready(() => {

      window.reloadData = 0;
      loadData();

   });
})(jQuery)

PS: It's recomended to replace just a div where the search results should appear, because you don't want to save the state of every single thing in your page every time :)

Upvotes: 1

Related Questions