Reputation: 1318
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.
Upvotes: 0
Views: 57
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
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());
})
});
Upvotes: 2