gpt4 book ai didi

javascript - 单击事件显示文本框长度

转载 作者:行者123 更新时间:2023-11-28 00:59:50 25 4
gpt4 key购买 nike

我试图在点击时显示文本框的长度。 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 上,我也想在将关键字添加到文本框时在 span 的文本中显示文本框长度(如果文本框长度 <80,则在单击事件后立即显示它)。

有人可以帮我吗?

最佳答案

为什么不使用函数来设置 #displayChar,如下所示:

function displayCharLength (count) {
$('#displayChar').text("Title contains: " + count + "/80 characthers");
}

在点击事件上附加关键字,然后获取计数:

var currentLength = $('.txtKeywords').val().length;

然后只需调用函数并传递长度:

displayCharLength(currentLength);

关于javascript - 单击事件显示文本框长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42671811/

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