-1

I am having trouble disabling a button. What I am trying to do is to disable the button unless typing some words in the input. The following is my code.

$('.btn.btn-default').click(function(){
    var post = $('input:text').val();
    $('<li>').text(post).prependTo('.posts');
    $('input:text').val("");
    $('.count').text('100');
    $('.btn.btn-default').addClass('disabled');
    });


$('input:text').keyup(function(){
    var postLength = (this).val().length;
    var charactersLeft = 100 - postLength;
    $('.count').text(charactersLeft);   
    if (charactersLeft < 0){
    $('.btn.btn-default').addClass('disabled');
    }
    else if (charactersLeft == 100){
        $('.btn.btn-default').addClass('disabled'); 
    }
    else{
        $('.btn.btn-default').removeClass('disabled');
    }
});

$('.btn.btn-default').addClass('disabled');

};

The following is my HTML

<div class= "blank">
    <input type="text" id="form-control" placeholder="Please Leave Comment Here."/>
    </div>


    <div class = "status">
    <div class= "count">100</div>
    <input class="btn btn-default" type="submit" value="Post">
    </div>

    <ul class="posts">
    </ul>
Femi
  • 3
  • 3
Yuan Huang
  • 21
  • 1
  • 1
  • 3

1 Answers1

6

TYPO:

(this).val().length;
^^^

Add the missing $. You should be an error in your console pointing out that "val is not a function".

Also adding a class does not disable a button. You need to set the property.

$(".btn.btn-default").prop('disabled', true);
$(".btn.btn-default").prop('disabled', false);
epascarello
  • 204,599
  • 20
  • 195
  • 236