gpt4 book ai didi

jquery - 显示输入长度的限制计数器

转载 作者:行者123 更新时间:2023-12-01 01:22:33 25 4
gpt4 key购买 nike

我使用下面的 jquery 将输入的长度限制为 110 个字符。补充一下,它显示输入了多少个字符,但是我想显示还剩下多少个字符。有什么帮助吗?另外,我将不胜感激任何有关如何改进此代码的建议。

jQuery(document).ready(function(){
jQuery("#post_title").prev("label").children(".adverts-form-required").after("<span class=\"title-counter\">(<input type=\"text\" value=\"0\" maxlength=\"3\" size=\"3\" id=\"title_counter\" readonly=\"\" style=\"background:#fff;\">)</span>");
jQuery("#post_title").keyup( function() {
jQuery("#title_counter").val(jQuery("#post_title").val().length);
});
jQuery(".adverts-field-text #post_title").keyup( function() {
var $this = jQuery(this);
if($this.val().length > 110)
$this.val($this.val().substr(0, 110));
});
});

输入字段:

<div class="adverts-control-group adverts-field-text">
<label for="post_title">Title
<span class="adverts-form-required">*</span>
</label>
<input name="post_title" id="post_title" type="text">
</div>

更新

更新了代码,感谢@dhaval-marthak。有用。问题是如何在 <span class="title-counter"></span> 中显示有关长度限制的默认信息。当输入长度等于0时标记?我试过这个:<span class="title-counter">\(the input limit is 110 characters\)</span> ,但是当我删除输入的文本时,它不再显示。

# add a span tag to display the counter
jQuery("#post_title").prev("label").children(".adverts-form-required").after("<span class=\"title-counter\"></span>");

# add an input length limit
jQuery("#post_title").keypress(function(){
if(this.value.length > 110){
return false;
}
jQuery(".title-counter").html("are left: " +(110 - this.value.length) +" characters");
});

最佳答案

只是在 HTML 中设置限制吗?它将被计数器覆盖。然后当文本区域为空时,重置 HTML。

基于@dhaval-marthak的回答:

HTML

<textarea></textarea>
<span id="remaining"></span>
<span id="limit">(the input limit is 110 characters)</span>

Javascript

$('textarea').keyup(function () {
if (this.value.length === 0) {
$('#limit').show();
$('#remaining').hide();
} else {
$('#limit').hide();
$('#remaining').show();
}

if (this.value.length > 110) {
return false;
}

$("#remaining").html("Remaining characters : " + (110 - this.value.length));
});

更新的 fiddle : http://jsfiddle.net/r34gM/185/

关于jquery - 显示输入长度的限制计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33751683/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com