Reputation: 341
I have been trying to implement to show the remaining characters on php ajax cal.. i got the same thing using javascript but not able to do in ajax php cal.. can any one help me on this?
<script type="text/javascript">
function txtCounters(id,max_length,myelement)
{
counter = document.getElementById(id);
field = document.getElementById(myelement).value;
field_length = field.length;
if (field_length <= max_length) {
//Calculate remaining characters
remaining_characters = max_length-field_length;
//Update the counter on the page
counter.innerHTML = remaining_characters;
}
}
</script>
<label for="txtName">Enter Your Text : </label>
<input type="text" id="txtName" size="50" maxlength="50" onkeyup="javascript:txtCounters('txtCounter',50,'txtName')">
<div id="txtCounter"><b>50</b></div>characters remaining.
Upvotes: 0
Views: 1075
Reputation: 3821
Easiest way is with this handy library: jQuery.Maxlength
<input type="text" maxlength="50"/>
<script>
$("input").maxlength();
</script>
It will automatically include the text characters left by generating this:
<input type="text" maxlength="50"/>
<div class="maxlength">50 characters left</div>
EDIT
For some reason you want to use AJAX to do this.
Web Side
<textarea id="textarea" name="texter"></textarea><br />
<span id="chars_remaining"></span> character(s) remaining.
$( "#textarea" ).keyup(function() {
var text = $('#textarea').val();
$.ajax({
url: "url/to/PHP.php",
type: "GET",
data: { text: text },
cache: false,
success: function (resp) {
$('#chars_remaining").html(resp);
}
});
});
PHP
<?php
$string = $_POST['text'];
$length = strlen($string);
if ((50 - $length) == 0)) {
echo 'No';
}
else {
echo (50 - $length);
}
Upvotes: 1