Clear Textarea And Reset Character Count Of Textarea
I have a text area. Underneath the text area I can display the count of the characters in the text area as the user types. I also have a button for the user to clear the contents o
Solution 1:
I notice a few problems in your code. First you are not resetting the textarea when you click the clear
. Second, you are binding a new event handler each time you call resetCharacterCount()
.
You should create a method that is responsible only for re-calculating the text count and display it. And you bind the events to textarea only on start up. Here is a working example: (Note that I don't know what numberal
is, but I believe it is formatting the word count, so all I did is to comment it up)
$(document).ready(function() {
// bind displaying the character count of the text area to the keyup event (function on base.html).var id_objective_details_elem = $('#id_objective_details');
// bind the eventbindCharacterCount('id_objective_details', 'id_char_count');
// calculate the word count on setup
displayCharacterCount.call(id_objective_details_elem, 'id_char_count');
// bind onClick event to reset button
$('#id_icon_reset').click(function(e) {
// clear the text in textarea
id_objective_details_elem.text('');
resetCharacterCount()
focusTextArea();
});
});
functiondisplayCharacterCount(id2) {
var charCount = $(this).val().length;
// uncomment the following line in your production project// numeral.language('{{ LANGUAGE_CODE }}');// var charCount = numeral($(this).val().length).format('0,0');
$("#" + id2).text(charCount);
}
functionbindCharacterCount(id1, id2) {
$('#' + id1).bind("keyup focus blur change", function () {
displayCharacterCount.call(this, id2);
});
}
functionresetCharacterCount() {
// instead of binding the events again, directly call displayCharacterCount
displayCharacterCount.call($('#id_objective_details'), 'id_char_count');
}
functionfocusTextArea() {
$('#id_objective_details').focus();
}
JSFiddle: https://jsfiddle.net/3ah7Lywg/
Solution 2:
I try this and it's work!
<textareacols="40"id="id_objective_details"maxlength="1000"name="objective_details"rows="10">Test</textarea><spanid="id_char_count"></span><span> of 1,000 character limit</span><iid="id_icon_reset"class="fa fa-ban blue_color icon_size20"rel="tooltip"html="true"data-placement="top"onclick="resetCharacterCount();focusTextArea();"title="Clear">clear</i><scriptsrc="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script><script>
$(document).ready(function() {
$('#id_objective_details').keyup(function(){
$('#id_char_count').text($('#id_objective_details').val().length);
});
});
functionresetCharacterCount() {
$('#id_char_count').text(0);
$('#id_objective_details').val('');
}
functionfocusTextArea() {
$('#id_objective_details').focus();
}
</script>
Post a Comment for "Clear Textarea And Reset Character Count Of Textarea"