简体   繁体   中英

How do I stop the execution of a certain javascript on page load

I am using query autocomplete to select members that I retrieve from a MySQL database. This portion of the code works correctly. Then I wrote a script that gets the value of the selected and appends it to a url and opens it. The script does that but it has problems.

First problem is when the file is loaded, it does not wait for the autocomplete text input to change but it executes when the page loads. I can hit the back button on the browser and it executes again, then the I hit the back button a third time it stays on the page. At this point I can type a letter into the text input and a list of choices is returned. I can then select one and the javascript appends the value and opens the new page with the information requested on it.

Second problem is after I select a member from the dropdown, I have to click away from the text input field before the autocompletechange fires. How can I get it to fire when I select but before I leave the text input?

Here is the HTML file:

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
    <script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
    <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
    <script type="text/javascript">
    $(function () {$('#theinput').autocomplete({source: 'search.php'});
    });
 </script>
 </head>
 <body>
   <input type="text" id="theinput" />
   <button type="button" onclick="ClearFields();">Clear</button>
   <script type="text/javascript">
   $(function myFunction ()  {
   $('#theinput').on('autocompletechange change', function () {
   location.href = 'dirlist.php?title=' + document.getElementById('theinput').value    
   }).change();
 });
 function ClearFields() {document.getElementById("theinput").value = "";}
 </script>
 </body></html>

You call the change function yourself, did you try without?

$(function myFunction ()  {
    $('#theinput').on('autocompletechange change', function () {
        location.href = 'dirlist.php?title=' + 
        document.getElementById('theinput').value    
    }); // <-- no .change() right here!
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM