0

I'm trying to make an input be enabled/dsabled if an input type text is either empty or not. Here is my jQuery code:

$(document).on('keyup', '#searchString', function(){
    searchString = $('#searchString');
   if(searchString.val().length > 0){
        $('#cmdSearch').attr('disabled', false);
    }
    else{
        $('#cmdSearch').attr('disabled', true);
    }
});

And here is the relevant HTML node:

<div class="form-wrapper">
     <form method="post" class="res-form" role="form">
     <input type="text" name="searchString" id="searchString" autocomplete="off" aria-autocomplete="none" class="form-control input-lg" placeholder="busca artículos, screencasts o demos">
     <div style="height: 15px;"></div>
     <button type="submit" name="cmdSearch" disabled="true" id="cmdSearch" class="btn btn-block btn-lg btn-success">Buscar</button>
     </form>
</div>

It works on desktop, though it doesn't on mobile. Any ideas why?

EDIT

I found something interesting, it does work, the problem is, that once I wipe out all the text from the input, let's say the input has a .val() of "foo" and I delete the "foo", I still have to press backspace once more so that the script takes action, this is happening on Android, on Chrome. This seems weird, any fix for this?

CodeTrooper
  • 1,890
  • 6
  • 32
  • 54

2 Answers2

1

For boolean you better use prop() instead of attr()

$(document).on('keyup', '#searchString', function(){
    searchString = $('#searchString');
   if(searchString.val().length > 0){
        $('#cmdSearch').prop('disabled', false);
    }
    else{
        $('#cmdSearch').prop('disabled', true);
    }
});
Adil
  • 146,340
  • 25
  • 209
  • 204
0

As you mentioned your new updates, i think you have to use $.trim() method to remove any whitespace from that element in the if condition:

$(document).on('keyup', '#searchString', function(){
    var searchString = $.trim($(this).val()); //<------make a local var instead
    if(searchString > 0){
        $('#cmdSearch').prop('disabled', false);
    } else {
        $('#cmdSearch').prop('disabled', true);
    }
});
Jai
  • 74,255
  • 12
  • 74
  • 103