Home > front end >  How to disable Search (enter and button) if it's empty or contains only spaces?
How to disable Search (enter and button) if it's empty or contains only spaces?

Time:06-27

How to disable Search form (input, enter, button) if it's empty or contains only white spaces?

Example code

<form id="example_form" >
  <input  type="text" placeholder="Search.." name="search">
  <button type="submit"><i ></i></button>
</form>

I have tried this jQuery code but it's not working.

$(document).ready(function() {
    $('.form_input').keyup(function() {
  
      var empty = false;
      $('.form_input').each(function() {
          if ($(this).val().length == 0) {
              empty = true;
          }
      });                   
  
      if (empty) {
          $('button[type="submit"]').attr('disabled', 'disabled');
      } else {
          $('button[type="submit"]').removeAttr('disabled');
      }                
    });
  });

CodePudding user response:

Consider the following.

$(function() {
  $.fn.isEmpty = function() {
    return $(this).val() == "" ? true : false;
  }

  $("#example_form").submit(function(event) {
    event.preventDefault();
    var valid = true;
    $(".form_input").each(function(i, el) {
      valid = valid && !$(el).isEmtpy();
    });
    return valid;
  });

  $("#example_form .form_input").keyup(function() {
    $("#example_form button[type='submit']").prop("disabled", $(this).isEmpty());
  });
});
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="example_form" >
  <input  type="text" placeholder="Search.." name="search">
  <button type="submit" disabled="true"><i ></i></button>
</form>

This does a few small thing. I have created a small Function to check if an Element is "empty", by checking the Value.

Using Submit callback, we can prevent the form from being submitted by using event.preventDefault(). We can then check each of the fields and if they are not empty, we can return true to continue submitting the form or false to prevent it.

CodePudding user response:

try this

if ($(this).val() === '') {
    return
}
do something.....
  • Related