I have a problem with downloading and displaying the value, when set to "rigidly" maxLenght - everything works fine, but when I want the script to download the value myself, I have a problem.
The script is supposed to get the value maxlenght = "" from each <input>
and after typing by the user it will print out how many characters are left.
var maxLen = document.getElementsByClassName("handlerWorld").maxLength;
function countChar(jqObj) {
var len = jqObj.val().length;
var diff = maxLen - len;
if (len > maxLen) {
len = maxLen;
diff = 0;
}
jqObj.val(jqObj.val().substr(0, len)).prev('label').find('span.chars-twenty').text(diff);
}
$(document).ready(function () {
$("[class*='handlerWorld']").keyup(function () {
countChar($(this));
}).each(function () {
countChar($(this));
});
});
My HTML:
<div >
<label for="nameIput">Nazwa firmy <span>Remaining: <span ></span></label>
<input type="text" id="name" maxlength="140" name="name" >
</div>
<div >
<label for="urlInput">URL <span>Remaining: <span ></span></label>
<input type="text" id="url" name="url" maxlength="100" >
</div>
Edit:
Now I would like it to show the number of characters, e.g .:
10/140
quantity written / quantity in the value "maxlenght"
$("#add-category").find('span.maxchar').text(maxLen);
They work but not as they should.
CodePudding user response:
Move the MaxLength calculation to the Count method
var maxLen = jqObj.attr("maxlength");
here's fiddle for you: https://jsfiddle.net/d53yjpr8/1/
function countChar(jqObj) {
var maxLen = jqObj.attr("maxlength");
var len = jqObj.val().length;
var diff = maxLen - len;
if (len > maxLen) {
len = maxLen;
diff = 0;
}
jqObj.val(jqObj.val().substr(0, len)).prev('label').find('span.chars-twenty').text(diff);
}
$(document).ready(function() {
$("[class*='handlerWorld']").keyup(function() {
countChar($(this));
}).each(function() {
countChar($(this));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<label for="nameIput">Test <span>Remaining:</span> <span ></span></label>
<input type="text" id="name" maxlength="140" name="name" >
</div>
<div >
<label for="urlInput">URL <span>Remaining:</span> <span ></span></label>
<input type="text" id="url" name="url" maxlength="100" >
</div>