0

I have this code :

$(document).ready(function() {
  $('#search').keyup(function() {
    var search = $('#search').val();
    console.log(search);
    if (search.length !== 0 || search !== "") {
      $('.wrapper').css({
        "background-color": "#000",
        "opacity": 0.8
      });
      $('.post').remove();
    } else {
      location.reload(false);
    };
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#">
  <button type="submit">Search</button>
  <input type="text" name="search" id="search" />
</form>

but the problem is that whatever put space at the beginning in the input element, the function is not working (it goes on to run $('.wrapper').css({"background-color":"#000","opacity":0.8}); and $('.post').remove(); ).

j08691
  • 197,815
  • 30
  • 248
  • 265
liontass
  • 652
  • 7
  • 22

3 Answers3

1

Just add search = search.trim(); before your conditional.

When you are adding a space to the input search is ' ' not '' so a trim is necessary.

Additionally, using:

if (search) {
    ....
}

instead of

if (search.length !== 0 || search !== '') {
    ...
}

Is a simpler check that will give you the same result in this case. Both '' and 0 are 'falsey'.

$(document).ready(function() {
  $('#search').keyup(function() {
    var search = $('#search').val();
    search = search.trim(); //Try adding this line
    console.log(search);
    if (search.length !== 0 || search !== "") {
      $('.wrapper').css({
        "background-color": "#000",
        "opacity": 0.8
      });
      $('.post').remove();
    } else {
      location.reload(false);
    };
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#">
  <button type="submit">Search</button>
  <input type="text" name="search" id="search" />
</form>
limeandcoconut
  • 418
  • 6
  • 21
0

Use String#trim to remove spaces before and after the text:

var search = $('#search').val().trim();

$(document).ready(function() {
  $('#search').keyup(function() {
    var search = $('#search').val().trim();

    if (search) {
      $('.wrapper').css({
        "background-color": "#000",
        "opacity": 0.8
      });
      $('.post').remove();
    } else {
      location.reload(false);
    };

  });

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#">
  <button type="submit">Search</button>
  <input type="text" name="search" id="search" />
</form>
Ori Drori
  • 166,183
  • 27
  • 198
  • 186
0

Just simply use ! or !! to check empty strings:

!"" // true
!!"" // false
pwolaq
  • 6,123
  • 18
  • 45
Yaser
  • 5,411
  • 1
  • 14
  • 26