0

I want to remove a class when nothing is inside of the input element, like in Google, when your search input is empty it won't show suggestions.

I have already tried this but it doesn't work:

$(".sc").keyup(function() {
  var x = $(this).val();
  $.post("search.php", { search: x }, function(checkSearch) {
    if (x == "") {
      $(".search").removeClass("searchOn");
      $(".search").html(checkSearch);
    } else {
      $(".search").html(checkSearch);
      $(".search").addClass("searchOn");
    }
  });
});

How can I fix it?

grooveplex
  • 2,131
  • 4
  • 24
  • 28
Shawn Vn
  • 287
  • 1
  • 12
  • 1
    `''` is not null. It's an empty string. – Taplar Apr 24 '19 at 20:03
  • 1
    x=='' won't catch null or undefined. see https://stackoverflow.com/questions/5515310/is-there-a-standard-function-to-check-for-null-undefined-or-blank-variables-in – daddygames Apr 24 '19 at 20:03
  • `$(".search").removeClass()("searchOn");` is also a logical error. Remove the empty `()` – Taplar Apr 24 '19 at 20:04
  • Possible duplicate of [jQuery: checking if the value of a field is null (empty)](https://stackoverflow.com/questions/4244565/jquery-checking-if-the-value-of-a-field-is-null-empty) – zod Apr 24 '19 at 20:09

3 Answers3

1

if(x == '') catches empty strings, not null.

Try using if(!x) instead (sees if x is null, undefined or empty string).

Anis R.
  • 5,631
  • 2
  • 8
  • 31
0

If you want to check if the input is null or undefined just compare with this values. An empty string (x = '') evaluates to true if you do !x. So if you only want to check then the value is null or undefined, do this.

$(".sc").keyup(function ()
     {
       const x=$(this).val();
       $.post('search.php',{search:x},function (checkSearch)
       {
           x === null || x === undefined 
            ? $(".search").removeClass("searchOn") 
            : $(".search").addClass("searchOn")

           $(".search").html(checkSearch);

       }
});
F.bernal
  • 2,294
  • 2
  • 19
  • 26
0

I have solved it I should have use === instead of ==

$(".sc").keyup(function ()
    {
       var x=$(this).val();
       $.post('search.php',{search:x},function (checkSearch)
       {
           if (x==='')
           {
               $(".search").removeClass("searchOn");
               $(".search").html(checkSearch);
           }
           else {
               $(".search").html(checkSearch);
               $(".search").addClass("searchOn");
           }
       });
Shawn Vn
  • 287
  • 1
  • 12