TShrestha
TShrestha

Reputation: 1318

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

Upvotes: 0

Views: 57

Answers (2)

K K
K K

Reputation: 18099

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

Upvotes: 1

Wouter Bouwman
Wouter Bouwman

Reputation: 1013

You are adding a click event for every character you type into the textarea. You should only add one click event.

$(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());
  })
});

http://jsfiddle.net/7uj6xt68/

Upvotes: 2

Related Questions