gpt4 book ai didi

javascript - 仅允许 td 中的数字,其中 contenteditable = true

转载 作者:行者123 更新时间:2023-11-30 13:47:02 25 4
gpt4 key购买 nike

我对这个简单的部分失去了理智。我有一个包含 20 多个列的表格,其中一些列是可编辑的,有些则不是。

我现在需要的是,当用户添加新行时,他被迫只在几个单元格中写入数字。到目前为止,我尝试了这里的示例:
accept only numbers in td
accept numbers using isNumeric()
两个都不行

只有在我对整个表调用函数时它才有效。但这是不可用的,因为还有一些单元格也应该接受字符串值。

$("#my_id").keydown(function(e) {
if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
((e.keyCode == 65 || e.keyCode == 86 || e.keyCode == 67) && (e.ctrlKey === true || e.metaKey === true)) ||
(e.keyCode >= 35 && e.keyCode <= 40)) {
return;
}
if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
e.preventDefault();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="my_id" border="1" width="100px" height="50px">
<thead></thead>
<tbody>
<tr>
<th>1</th>
<td class="allow_only_numbers" contenteditable="true" id="idid"></td>
</tr>
</tbody>
</table>

这个特定的代码在这里(在 Stackoverflow 上)不起作用,因为第一个链接的脚本不包括在内:(但如果我将它添加到我现有的代码中,它将起作用)

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

但是如果我在我的代码中插入脚本部分,那么日期选择器就会出现问题......我无法使用它......我的猜测是,它可能很容易纠正,但我无法弄清楚 -.-

更新我设法纠正了它。添加新行时我需要“唯一的数值”,在此之前它是无用的。所以我在“添加行”函数中添加了这个函数,现在它可以工作了。谢谢大家的帮助

最佳答案

试试这个..

$(".allownumeric").on("keypress keyup blur", function(event) {
$(this).val($(this).val().replace(/[^\d].+/, ""));
if ((event.which < 48 || event.which > 57)) {
event.preventDefault();
}
});

$(".allowstring").on("keypress keyup blur", function(event) {
$(this).val($(this).val().replace(/[^\w].+/, ""));
if (!((event.which >= 65 && event.which < 92) ||
(event.which >= 97 && event.which <= 122))) {
event.preventDefault();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<table id="my_id" border="1" width="200px" height="50px">
<thead>
<tr>
<th>1 (only num)</th>
<th>2 (only str)</th>
</tr>
</thead>
<tbody>
<tr>
<td class="allownumeric" contenteditable="true"></td>
<td class="allowstring" contenteditable="true"></td>
</tr>
</tbody>
</table>

关于javascript - 仅允许 td 中的数字,其中 contenteditable = true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59105526/

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