我正在尝试在点击时显示文本框长度。 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"></span>
</div>
最初在页面加载时,我将附近范围的文本设置为以下文本:
$('#displayChar').text("Title contains: 0/80 characthers");
如果用户在文本框中输入内容,则此事件会跟踪更改,文本框长度的相应值将显示如下:
$('.txtKeywords').on('keyup',function(){
var input = $(this);
input.next("span").text("Title contains: "+ input.val().length + "/80 characthers");
});
这一切都很好。我还通过将输入属性“maxlength”设置为80个字符来设置HTML 5文本框验证...
现在我想在附近的桌子上点击td显示文本框长度,它基本上显示了产品的标题以及我在上面的输入文本框中组装的内容,如下所示(这是HTML标记):
<tr>
<td class="keywordClick" value="@item.Keyword"><h5 style="cursor:pointer;">@item.Keyword</h5></td>
<td><b>@item.Sales</b></td>
</tr>
组装标题的事件/代码是:
$(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.")
}
});
在这最后甚至是.keywordClick我想在文本框中添加关键字时显示文本框长度(如果文本框长度<80,则在点击事件后立即显示)。
有人能帮助我吗?
答案 0 :(得分:1)
为什么不使用函数来设置 #displayChar ,如下所示:
function displayCharLength (count) {
$('#displayChar').text("Title contains: " + count + "/80 characthers");
}
在点击事件上附加关键字,然后获取计数:
var currentLength = $('.txtKeywords').val().length;
然后只需调用该函数并传递长度:
displayCharLength(currentLength);
答案 1 :(得分:0)
事实证明这很好用:
$("#displayChar").text(function(index,val){
return "Title contains: "+ $('.txtKeywords').val().length + "/80 characthers";
});