【问题标题】:Need to filter input to only two decimal places in a Table <td> ContentEditable需要在表 <td> ContentEditable 中将输入过滤到小数点后两位
【发布时间】:2021-12-28 22:36:23
【问题描述】:

首先,如果这是我的愚蠢,请道歉。我在 Stackoverflow 上进行了搜索,并在 Google 上搜索了这个,但没有找到任何与我想要完成的任务类似的东西。

我有一个表格,表格中有几列带有 ContentEditable 标记,我正在尝试设置一些内容,以便将输入限制为仅 2 位小数以包含货币。

到目前为止我所拥有的 - 因为它以输入标签为目标,所以它不起作用。

(function($) {
  $.fn.inputFilter = function(inputFilter) {
    return this.on("input keydown keyup mousedown mouseup select contextmenu drop", 
function() {
      if (inputFilter(this.value)) {
        this.oldValue = this.value;
        this.oldSelectionStart = this.selectionStart;
        this.oldSelectionEnd = this.selectionEnd;
      } else if (this.hasOwnProperty("oldValue")) {
        this.value = this.oldValue;
        this.setSelectionRange(this.oldSelectionStart, this.oldSelectionEnd);
      } else {
        this.value = "";
      }
    });
  };
}(jQuery));

$(document).ready(function() {
  $("#currencyTextBox").inputFilter(function(value) {
    return /^\d*$/.test(value);    // Allow digits only, using a RegExp
  });
});

HTML 方面

        <table id="QuoteTable" class="table table-bordered table-responsive-md table- 
    striped text-center">
    <thead class="bg-white">
      <tr>
        <th class="text-center">Stock Code</th>
        <th class="text-center">Item Description</th>
        <th class="text-center">Quantity of Item</th>
        <th class="text-center">Unit Cost Exc VAT (£)</th>
        <th class="text-center">Unit Cost Inc VAT (£)</th>
        <th class="text-center">Total Cost</th>
        <th class="text-center">Remove from List</th>
      </tr>
    </thead>
    <tbody id="Products" class="bg-white">
        <tr>
        <td contenteditable='true'></td>
        <td contenteditable='true'></td>
        <td contenteditable='true'>1</td>
        <td id="currencyTextBox" contenteditable='true'>0.00</td>
        <td id="currencyTextBox" contenteditable='true'>0.00</td>
        <td class="bg-secondary" contenteditable='false'></td>
        <td class="bg-secondary" contenteditable='false'></td>
        </tr>

    </tbody>
    </table>

如果有人知道任何其他方法,我可以让我的 contentEditable td 标签限制输入,我很想听听。

由于网站其余部分的样式以及之后我将表格数据发送到数组的方式,我无法在 td 标记内使用输入标记。

【问题讨论】:

  • 您将需要使用innerText 而不是value,因为您没有使用输入。
  • 谢谢布伦登!成功了,你是个传奇。
  • 我将添加反馈作为未来访问者的答案。我相信你会意识到setSelectionRange 也会有同样的问题。
  • 是的,谢谢,我阅读了 value 和 innerHTML 之间的区别,现在明白了。我删除了 setSelection 行,我将放置一些代码以将其自动移动到下一个框。

标签: javascript html jquery html-table contenteditable


【解决方案1】:

由于您没有使用Input 元素,因此值将是未定义的。您将需要改用innerText。这将是节点的文本值。

【讨论】:

    猜你喜欢
    • 2012-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-02
    • 1970-01-01
    • 2018-10-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多