简体   繁体   中英

How to disable search button after first click until results come from server

 <form action="action_page.php"> Search Google: <input type="search" name="googlesearch"> <input type="submit"> </form> 

When I enter something into input field for the first time and then click on search button it should be disabled but until the related results come and it should be enabled again. Or other option is that after first search-click the input field should become empty or clear after related results come and I can make the button enabled again when I will focus for the input field for the second time for second time search.

Try preventing the default behaviour of the form by using event.preventDefault() , add the relevant code you like it to do, then ensure a callback is added to your result fetching function that makes the button enabled again when it's done (this will depend on how you're doing this exactly).

The bit that takes care of the preventing could look something like this (merged with your original code):

 $("input[type='submit']").click(function(event) { event.preventDefault(); $(this).attr('disabled', true); // do your form posting, then add in its 'success' function the following: // $(the_original_submit_button).removeAttr('disabled'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form action="action_page.php"> Search Google: <input type="search" name="googlesearch"> <input type="submit"> </form> 

Note: the the_original_submit_button selector has been explicitly named so, as if you're using it inside another function that takes care of the form posting (like AJAX for example), the selector for the submit button may not be this (it will probably become the object of the AJAX call, again, assuming you're using AJAX), so you're going to have to pass it inside your function somehow, eg. by defining it as a variable.

如果使用的是ajax,则可以在ajax readyState <4时将onsubmit事件设置为return false

Here is how it can be done. First remove action="action_page.php" from form tag because it will call form submit method which we don't want.

When search button is clicked we will disable it until we will get response from server.

Here is a prototype code.

$('#submit-btn').click(function(){
 $('#submit-btn').attr('disabled',true); // Disable button
 $.ajax({
   type: 'POST'
   url: 'action_page.php',
   data: {
      searchWords:$('search-inp').val()
   },
   success: function(data) { // After Success
        doSomethingWithData(data);
        $('#submit-btn').attr('disabled',false); // Enable button
   },
 });
});

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