Dynamic text restriction when users write to a text field (HTML)

I need to implement in Html / javascript (possibly php) a script that works like twitter when the user writes text in a field with a label change with the remaining characters.

Can you help me with an example of a simple and simple script?

+3
source share
3 answers
<script>
function checkCharCount(textfield){
    if(textfield.value.length > 300) textfield.value = textfield.value.substr(0, 300);
    document.getElementById("charCounter").innerHTML = 300 - textfield.value.length;
}
</script>

<textarea class="input" name="REMARK" rows="5" cols="45" maxlength="300" wrap="virtual" onKeyUp="checkCharCount(this);"></textarea> 
<div><span id="charCounter">300</span> characters left.</div> 
+2
source

Tim Down , , . , , - ( ) , , javascript . (, )

<head>
<script>
function checkCharCount(){
    textfield = document.getElementById('remark');
    //if(textfield.value.length > 300) // does not register length change until the next paste or keyup
    textfield.value = textfield.value.substr(0, 300);
    document.getElementById("charCounter").innerHTML = 300 - textfield.value.length;
}
</script>
</head>
<body>

<textarea id="remark" class="input" name="remark" rows="5" cols="45" wrap="virtual" onkeyup="checkCharCount();" onpaste="setTimeout(checkCharCount, 20);"></textarea> 
<div><span id="charCounter">300</span> characters left.</div>

</body>

. http://www.quirksmode.org/dom/events/cutcopypaste.html -, ,

+1

I would use a jQuery plugin like this one . It is possible to do this with PHP, but it would be nice .. well .. wrong. Since PHP runs on the server, you have to send / receive to the server with every keystroke. Javascript works on the client side, so this extra payload is not needed. Hover over the maximum value in PHP, send it to the client in the original response, and use it in client-side JavaScript.

0
source

Source: https://habr.com/ru/post/1747696/


All Articles