我一直在尝试实现在php ajax cal上显示剩余的字符..我使用javascript但是无法在ajax php cal中做同样的事情..任何人都能帮助我吗?
<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.
答案 0 :(得分:1)
这个方便的库最简单:jQuery.Maxlength
<input type="text" maxlength="50"/>
<script>
$("input").maxlength();
</script>
它会自动包含生成此文件所留下的文字字符:
<input type="text" maxlength="50"/>
<div class="maxlength">50 characters left</div>
<强> 修改 强>
出于某种原因,您想使用AJAX来执行此操作。
网络方
<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);
}