将contentEditable单元格的输入类型动态更改为“数字”

时间:2018-12-01 09:43:12

标签: javascript html contenteditable

im将行动态插入表中

var cell1 = row.insertCell(0);
cell1.contentEditable = true;

我将contentEditable设置为true,但我希望将输入字段的类型设置为数字,而不是默认类型:“文本”。

2 个答案:

答案 0 :(得分:0)

类似于这篇文章:Contenteditable allow numbers only for editing?

实际上,td对象似乎没有要设置的type属性,因此可以使用输入或创建事件处理程序来验证输入。

答案 1 :(得分:0)

如上所述,您无法将属性type="number"设置为<td>,但是在此示例中使用javascript验证输入

function addTD() {
  var row = document.getElementById("myRow");
  var x = row.insertCell(0);
  x.contentEditable = true;
  x.onkeypress = function(ev) {
    if (isNaN(String.fromCharCode(ev.which))) {
      console.log('input number only');
      ev.preventDefault();
    }
  }
}
table,td{border:1px solid #000}
table{border-collapse:collapse}
td{display:inline-block;width:70px;text-align:center;height: 22px;}
[contenteditable=true]{background-color:#ccc}
[contenteditable=true]:focus{background-color:#ff0}
<table>
  <tr id="myRow">
    <td>First</td><td>Second</td>
  </tr>
</table>
<button onclick="addTD()">Add</button>