简体   繁体   English

如何仅在 html 的输入文本框中键入唯一字母或做出反应?

[英]How to type unique letters only in input text box in html or react?

I want to create an input box that allows to type only a distinct alphabet letter in the input box ( No duplicate alphabet value, ONLY ONE)我想创建一个输入框,只允许在输入框中输入一个不同的字母(没有重复的字母值,只有一个)

I looked up all the attributes for input box but I couldn't find one and there were no example.我查找了输入框的所有属性,但找不到一个,也没有示例。

Do I have to handle it within JavaScript functions?我必须在 JavaScript 函数中处理它吗? (I am using React) (我正在使用 React)

<input
            className="App-Contain-Input"
            name="containedLetter"
            type={"text"}
            onChange={containedChange}
          />

Here is how this can be done, note that we have to use onkeydown which fires when a key is being pressed, but not before it is being released (this way we can intercept and prevent the key stroke from being taken into account):这是如何做到这一点的,请注意,我们必须使用onkeydown ,它会在按下键时触发,但不会在释放键之前触发(这样我们就可以拦截并防止击键被考虑在内):

function MyInput() {

  const containedChange = (event) => {
    if (event.key.length === 1 && event.code.startsWith('Key') && event.code.length === 4 && event.target.value.indexOf(event.key) !== -1) {
      event.preventDefault()
      return false;
    }
    
    return true
  }
          
          
  return (
    <input
      id="input"
      className="App-Contain-Input"
      name="containedLetter"
      type="text"
      onkeydown={containedChange}
    />
}

Use a state to maintain the current value of the input.使用 state 来维护输入的当前值。 Then when the value changes get the last letter of the input, check that it's a letter, and if it is a letter and it isn't already in the state, update the state with the new input value.然后当值更改时获取输入的最后一个字母,检查它是一个字母,如果它是一个字母并且它不在 state 中,则用新的输入值更新 state。

 const { useState } = React; function Example() { const [ input, setInput ] = useState(''); function handleChange(e) { const { value } = e.target; const lastChar = value.slice(-1); const isLetter = /[a-zA-Z]/.test(lastChar); if (isLetter &&.input;includes(lastChar)) { setInput(value). } } function handleKeyDown(e) { if (e.code === 'Backspace') { setInput(input,slice(0. input;length - 1)); } } return ( <input value={input} onChange={handleChange} onKeyDown={handleKeyDown} /> ). } ReactDOM,render( <Example />. document;getElementById('react') );
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script> <div id="react"></div>

An isogram is a word with no repeating letters. isogram是没有重复字母的单词。 You can check this using regex您可以使用regex检查

function isIsogram (str) {
    return !/(.).*\1/.test(str);
}

Or using array.some或者使用array.some

function isIsogram(str) {
    var strArray = str.split("");
     return !strArray.some(function(el,idx,arr){
       return arr.lastIndexOf(el)!=idx;
     });
}

In react - you need to use state to reject inputs which contain repeated letters (not an Isogram ).react中 - 您需要使用 state 来拒绝包含重复字母(不是Isogram )的输入。 Complete example on codesandbox . codesandbox上的完整示例。

import { useState } from 'react';

export default function App() {
  const [ text, setText ] = useState('');

  function isIsogram(str) {
    var strArray = str.split("");
     return !strArray.some(function(el,idx,arr){
       return arr.lastIndexOf(el)!==idx;
     });
}

  function handleChange(e) {
    const { value } = e.target;
    console.log(isIsogram(value));
    if (value.length === 1 || isIsogram(value)) {
      setText(value);
    }
  }

  return (
    <input value={text} onChange={handleChange} />
  );
}

Your containedChange function can be like this:你的containedChange function 可以是这样的:

const containedChange = (e) => {
    const value = e.target.value;
    const lastChar = value[value.length - 1];

    if (value.slice(value.length - 1, value.length).indexOf(lastChar) != -1) {
        // show error message
    }

The function checks whether the last entered character already exists in the previous value or not. function 检查最后输入的字符是否已经存在于先前的值中。

A way to do it with a cheeky two-liner is to get rid of any non-letters with regex, then let Set do the de-duping by converting to Array => Set => Array => String:一种使用厚颜无耻的双行代码的方法是用正则表达式去除任何非字母,然后让 Set 通过转换为 Array => Set => Array => String 来进行重复数据删除:

As a side note, many of the other solutions posted here make one or both of two assumptions:作为旁注,此处发布的许多其他解决方案都做出了两个假设中的一个或两个:

  1. The user is only ever going to edit the last character... but what if they edit from the beginning or middle?用户只会编辑最后一个字符……但是如果他们从开头或中间开始编辑怎么办? Any last character solution will then fail.任何最后一个字符解决方案都将失败。
  2. The user will never copy/paste a complete value... again, if they do, most of these solutions will fail.用户永远不会复制/粘贴完整的值……同样,如果他们这样做,大多数这些解决方案都会失败。

In general, it's best to be completely agnostic as to how the value is going to arrive to the input, and simply deal with the value after it has arrived.通常,最好完全不知道值将如何到达输入,并在它到达后简单地处理该值。

import { useState } from 'react';

export default function Home() {
    const [value, setValue] = useState('');

    return (
        <div>
            <input
                type='text'
                value={value}
                onChange={(e) => {
                    const onlyLetters = e.target.value.replace(/[^a-zA-Z]/g, '');
                    setValue(Array.from(new Set(onlyLetters.split(''))).join(''));
                }}
            />
        </div>
    );
}

One pure js solution would be to handle the input value in onkeyup event where we have access to the latest key as well as updated input target value.一种纯 js 解决方案是在 onkeyup 事件中处理输入值,我们可以在其中访问最新的键以及更新的输入目标值。

If the latest key pressed is duplicate then we will found it on 2 location in the target value, first on some where middle of the target value and second at the end of the target value.如果最近按下的键是重复的,那么我们将在目标值的 2 个位置找到它,第一个是在目标值的中间,第二个是在目标值的末尾。 So we can remove the value at the end (which is the duplicate one).所以我们可以删除最后的值(这是重复的)。

The below code snippet shows the implementation of above in React下面的代码片段显示了上面在 React 中的实现

const Input = () => {
  const handleKeyUp = (e) => {
    const { key, target: { value }} = e;
    const len = value.length;

    if (value.indexOf(key) < len - 2) {
        e.target.value = value.slice(0, len - 1);
    }
  }

  return (
    <div>
      <label>Unique Keywords</label>
      <input type="text" placeholder="my-input" onKeyUp={handleKeyUp} />
    </div>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM