How to stop multiple calls on some events in Jquery?

I am trying to check the length of the input from a text area in my page. For this I have done as below:

    <textarea id="reviews_comment" name="comment" value="<?php echo $this->input->post('comment'); ?>" ></textarea>
    <button style="display: none;" id="comment_button" class="btn btn-success"  >Add Comment</button>

The associated script is as under:

  <script type="text/javascript">
    $(document).ready(function(){

     $('#reviews_comment').bind('input propertychange', function() {

     var review = $('#reviews_comment').val()
        if(review.length>=4){
           $('#comment_button').show();
           $('#comment_button').on('click',function(){
            alert($('#reviews_comment').val());
           })
        }
      })

     });
    </script>

When I do this, on clicking 'Add comment button' I get alert for multiple times if more that 4 letters are input. But if I input just 4 letters then it alerts only one time. Also when I alert review.length it alerts starting from 4 up to the number of letters entered. What is the real issue here? Any kind of help are highly appreciated. Thanks.

picture

Answers 1

  • Move the event binding out:

        $(document).ready(function() {
    
            $('#reviews_comment').bind('input propertychange', function() {
    
                var review = $('#reviews_comment').val()
                if (review.length >= 4) {
                    $('#comment_button').show();
    
                }
            });
            $('#comment_button').on('click', function() {
                alert($('#reviews_comment').val());
            });
    
        });
    

    Demo: http://jsfiddle.net/GCu2D/2208/

    The event is rebinded again everytime user types something in the textarea


Related Articles