【问题标题】:How do I make it so that <Input> only allows alphabet, whitespace and backspace?如何使 <Input> 只允许字母、空格和退格?
【发布时间】:2021-05-16 10:11:35
【问题描述】:

我有一个 15 x 15 的 html 表格形式的矩阵,每个单元格中都有一个输入框。我希望它让用户只能:

  • 输入英文字母
  • 删除一个字符(退格)
  • 使用空格键
  • 以后,我希望他们能够使用箭头键来导航矩阵

到目前为止,下面的代码允许我检查它是否是英文字母,但我不能使用退格键、空格键,也不能更新单元格。

以下是我的矩阵代码以及我如何更新值:

  const matrix = [];
  for(let i = 0; i < 15; i++){
    const row = [];
    for(let j = 0; j< 15; j++){
      row.push("")
    }
    matrix.push(row)
  }
  const [board,setBoard] = useState(matrix);
  const handleBoardChange = (event,row,col) => {
    if((event.target.value.charCodeAt(0) >= 65 && 
    event.target.value.charCodeAt(0) <= 90) || 
    event.target.value.charCodeAt(0) === 32 ||
    (event.target.value.charCodeAt(0) >= 97 && 
    event.target.value.charCodeAt(0) <= 122))
    {
      let copy = [...board]
      copy[row][col] = event.target.value
      setBoard(copy)}
    }
  return (
    <div className="analysis-section">
      <Board 
        board={board}
        handleBoardChange ={handleBoardChange}
      />
    </div>
  );
}

这是矩阵本身:

const Board = ({board,handleBoardChange}) => {
  let rows = [];
    for (var i = 0; i < 15; i++){
      let rowID = `row${i}`
      let cell = []
      for (var idx = 0; idx < 15; idx++){
        let cellID = `cell${i}-${idx}`
        let row = `${i}`
        let col = `${idx}`
        cell.push(
        <td key={cellID} id={cellID}>
          <div>
            <input 
              type="text" 
              maxLength="1" 
              value = {board[parseInt(row)][parseInt(col)]}
              onChange = {(e) => {
              handleBoardChange(e,parseInt(row),parseInt(col))}
              }
            >
            </input>
          </div>
        </td>)
      }
      rows.push(<tr key={i} id={rowID}>{cell}</tr>)
    }
  return (
    <div className="board">
      <table>
        {rows}
      </table>
    </div>
  );
}

export default Board

感谢您的帮助,谢谢!

【问题讨论】:

    标签: javascript html reactjs


    【解决方案1】:

    此功能将阻止接受英文字母以外的字母,它还允许退格和空格键,以及箭头键。

     const onChange = (e) => {
    let value = e.target.value;
    
    value = value.replace(/[^A-Za-z _]/gi, "");
    setValue(value);
    };
    

    sandbox

    【讨论】:

    • 它有效,非常感谢。你知道我如何集成左箭头功能来导航表格吗?
    猜你喜欢
    • 1970-01-01
    • 2018-06-04
    • 1970-01-01
    • 2013-11-04
    • 2017-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多