In my project, I am showing the remaining character length for a textarea for adding reviews, in a span while user types on the textarea.
The following is the keypress event :
$('#reviewtxt').keypress(function(){
if($('#reviewtxt').val().length > 1000){
return false;
}
if($.trim($('#reviewtxt').val()) != "")
{
$("#reviewremaining").html("Remaining Characters : " +(1000 - $('#reviewtxt').val().length));
}
});
HTML Code for the textarea
$data = array(
'name' => 'reviewtxt',
'id' => 'reviewtxt',
'value' => '',
'rows' => '10',
'cols' => '50',
'style' => 'border-radius:3px;border:1px solid rgba(75,156,255,1);margin-top:10px;',
'placeholder' => lang('type_here').' (Press Enter key to send your review) ',
'onkeypress' => 'submitreview(\''.base_url().'\',\''.$pgmresult->id.'\',\''.$id.'\',event,\'0\')'
);
echo form_textarea($data);?>
<span id='reviewremaining' style="color:red;font-size: 13px;"></span>
AJAX :
function submitreview(baseurl,videoid,userid,e,type)
{
$("#reviewremaining").show();
$("#reviewremaining").html('');
var reviewtxt=$.trim($("#reviewtxt").val());
if (e.keyCode == 13 || e.which == 13)
{
if(reviewtxt=="")
{
$("#reviewremaining").html('Please enter your review');
$("#reviewtxt").focus();
return false;
}
else
{
if(reviewtxt.length>1000)
{
$("#reviewremaining").html('Review cannot exceed more than 1000 characters');
$("#reviewtxt").focus();
return false;
}
$.ajax({
type:"post",
dataType:"text",
data:"reviewtxt="+reviewtxt+"&videoid="+videoid+"&userid="+userid+"&type="+type,
url:baseurl+"video/submitreview",
success:function(response)
{
}
});
}
}
}
Now the problem is that, I am able to press another key even if the length exceeds the maximum. Suppose the maximum length is 500 characters then, the function will return false
only when I press 501th character so that I need to delete that character in order to save the review. Also I want to show the remaining characters when I click on backspace or delete button.
Currently if I type 300 characters, then it will show Remaining characters : 300, then if I copy-paste some other lines, the text in span will still remain as same.
How to fix this problem? Can anyone help e to fix this?
Thanks in advance.