我正在尝试在单击时显示文本框长度。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>
最初,当页面加载时,我将附近span的文本设置为以下文本:
$('#displayChar').text("Title contains: 0/80 characthers");
如果用户在textbox中输入内容,此事件将跟踪更改,textbox的相应长度值显示如下:
$('.txtKeywords').on('keyup',function(){
var input = $(this);
input.next("span").text("Title contains: "+ input.val().length + "/80 characthers");
});
这一切都很好用。我还设置了HTML5文本框验证,将输入属性"maxlength“设置为80个字符...
现在我只想在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上,我也想在向文本框添加关键字时,在跨度的文本中显示文本框长度(如果textbox长度小于80,则在单击事件后立即显示它)。
有人能帮帮我吗?
发布于 2017-03-08 13:19:45
为什么不使用如下所示的函数来设置#displayChar:
function displayCharLength (count) {
$('#displayChar').text("Title contains: " + count + "/80 characthers");
}
将关键字追加到单击事件上,然后获取计数:
var currentLength = $('.txtKeywords').val().length;
然后只需调用函数并传递长度:
displayCharLength(currentLength);
发布于 2017-03-08 13:20:39
这被证明工作得很好:
$("#displayChar").text(function(index,val){
return "Title contains: "+ $('.txtKeywords').val().length + "/80 characthers";
});
https://stackoverflow.com/questions/42671811
复制