Javascript 单击事件时显示文本框长度
我试图在单击时显示文本框的长度。HTML标记如下所示:Javascript 单击事件时显示文本框长度,javascript,jquery,html,events,textbox,Javascript,Jquery,Html,Events,Textbox,我试图在单击时显示文本框的长度。HTML标记如下所示: <div class="title" style="padding:20px 0 "> <input type="text" class="form-control txtKeywords" maxlength="80" placeholder="Click on keywords to combine your title"> <span id="displayChar"></s
<div class="title" style="padding:20px 0 ">
<input type="text" class="form-control txtKeywords" maxlength="80" placeholder="Click on keywords to combine your title">
<span id="displayChar"></span>
</div>
如果用户在文本框中输入内容,则此事件将跟踪更改,文本框长度的相应值如下所示:
$('.txtKeywords').on('keyup',function(){
var input = $(this);
input.next("span").text("Title contains: "+ input.val().length + "/80 characthers");
});
这一切都很好。我还通过将输入属性“maxlength”设置为80个字符来设置HTML5文本框验证
现在,我只想在td单击附近的表中显示文本框的长度,该表基本上显示了产品的标题以及我在上面的输入文本框中组装的人,如下所示(这是HTML标记):
@item.Keyword
@项目.销售
组装标题的事件/代码为:
$(document).on("click", ".keywordClick", function () {
var appendText = " " + $(this).attr('value');
if ($('.txtKeywords').val().length < 80) {
// somehow here modify the span value to display .txtKeywords current length
$('.txtKeywords').val(function (index, val) {
return val+appendText;
});
}
else {
ShowErrorMessage("Title can have maximum of 80 characters.")
}
});
$(文档)。在(“单击“,”上。关键字单击“,函数(){
var appendText=”“+$(this.attr('value');
if($('.txtKeywords').val().length<80){
//不知何故,在这里修改跨度值以显示.txtKeywords当前长度
$('.txtKeywords').val(函数(索引,val){
返回val+appendText;
});
}
否则{
消息(“标题最多可包含80个字符。”)
}
});
在最后一篇文章中,我想在文本框中添加关键字时,在span的文本中显示文本框的长度(如果文本框长度为为什么不使用函数设置#displayChar,则在单击事件后立即显示它,如下所示:
function displayCharLength (count) {
$('#displayChar').text("Title contains: " + count + "/80 characthers");
}
将关键字附加到click事件上,然后获取计数:
var currentLength = $('.txtKeywords').val().length;
然后只需调用函数并传递长度:
displayCharLength(currentLength);
结果证明,这一切都很好:
$("#displayChar").text(function(index,val){
return "Title contains: "+ $('.txtKeywords').val().length + "/80 characthers";
});
@AshishBahl不确定我是否理解你的意思?你能澄清一下你的意思吗?我想你有很多
.txtKeywords
元素,对吗?@Rayon第三次幸运…不。txtKeywords只是一个输入…keywordClick元素是多个,因为它是由控制器操作生成的表:DAnyone guys?=)
displayCharLength(currentLength);
$("#displayChar").text(function(index,val){
return "Title contains: "+ $('.txtKeywords').val().length + "/80 characthers";
});