如何只接受唯一的值在一个数字输入类型在一个表格中的html?

4jb9z9bj  于 2023-06-20  发布在  其他
关注(0)|答案(1)|浏览(86)

我有一个带有数字输入类型的表单,我的响应限制在1到14之间。但是,我想让用户只输入1到14之间的唯一数字。例如,如果他们为三个不同的输入框输入“2”,我希望弹出一个警告,不让他们提交,直到他们修复。
有人帮助我,给了我这个,但它似乎不起作用。我没有正确使用它吗?

document.getElementById("formName").addEventListener("submit", function(event) {
  // Here you get all unique-number inputs.
  var inputs = Array.from(document.getElementsByClassName('unique'));
  
  // After that you map each input.
  var values = inputs.map(function(input) {
    return parseInt(input. Value, 10);
  });

  // An if to know if there are any duplicate values.
  if (hasDuplicates(values)) {
    event.preventDefault();
    alert("Please ensure all numbers are unique.");
  }
});

function hasDuplicates(array) {
  var valueCount = {};
  
  for (var i = 0; i < array.length; i++) {
    if (valueCount[array[i]]) {
      return true;
    }
    valueCount[array[i]] = true;
  }

  return false;
}

这就是我的数字输入的样子。

<label><input type="number" name="num" min="1" max="14" autocomplete="off" oninvalid="this.setCustomValidity('Please enter a number between 1 and 14')" oninput="this.setCustomValidity('')" class="unique"> <span>Mark Twain</span></label>
<br>

我使用<script src="script.js"> </script>将javascript包含到我的htmlpage中
我是不是在html中实现了错误的代码?它实际上不工作吗?请帮帮忙,谢谢!

kmynzznz

kmynzznz1#

根据我的基准测试(在答案下面),使用Set是处理唯一值的最快方法:

document.getElementById("formName").addEventListener("submit", e => {
  
  const values = Array.from(e.target.querySelectorAll('.unique'))
    .map(input => parseInt(input.value)).filter(num => num === num);

  try {

    // An if to know if there are any duplicate values.
    if (!isUnique(values)) {
      throw new Error("Please ensure all numbers are unique.");
    }
  
  } catch (err) {
    alert(err.message);  
    e.preventDefault();  
  }
  
  
});

function isUnique(arr) {
  const set = new Set;
  for (let i = 0; i < arr.length; i++) {
      const val = arr[i];
      if (set.has(val)) {
          return false;
      }
      set.add(val);
  }
  return true;
}
<form id="formName">
<label><input type="number" name="num" min="1" max="14" autocomplete="off" oninvalid="this.setCustomValidity('Please enter a number between 1 and 14')" oninput="this.setCustomValidity('')" class="unique"> <span>Mark Twain</span></label>
<br><label><input type="number" name="num" min="1" max="14" autocomplete="off" oninvalid="this.setCustomValidity('Please enter a number between 1 and 14')" oninput="this.setCustomValidity('')" class="unique"> <span>Mark Twain</span></label>
<br><label><input type="number" name="num" min="1" max="14" autocomplete="off" oninvalid="this.setCustomValidity('Please enter a number between 1 and 14')" oninput="this.setCustomValidity('')" class="unique"> <span>Mark Twain</span></label>
<br><label><input type="number" name="num" min="1" max="14" autocomplete="off" oninvalid="this.setCustomValidity('Please enter a number between 1 and 14')" oninput="this.setCustomValidity('')" class="unique"> <span>Mark Twain</span></label>
<br><label><input type="number" name="num" min="1" max="14" autocomplete="off" oninvalid="this.setCustomValidity('Please enter a number between 1 and 14')" oninput="this.setCustomValidity('')" class="unique"> <span>Mark Twain</span></label>
<br>
<button>Submit</button>
</form>
<body></body>
<script name="benchmark" data-count="1">

    const count = 1000000;
    const arr = Array.from({ length: count }, () => Math.random());

    function isUnique(arr) {
        const set = new Set;
        for (let i = 0; i < arr.length; i++) {
            const val = arr[i];
            if (set.has(val)) {
                return false;
            }
            set.add(val);
        }
        return true;

    }
    function isUnique2(arr) {
        const set = {};
        for (let i = 0; i < arr.length; i++) {
            const val = arr[i];
            if (val in set) {
                return false;
            }
            set[val] = true;
        }
        return true;
    }

    // @benchmark using Set
    isUnique(arr);

    // @benchmark using object
    isUnique2(arr);

</script>
<script src="https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js"></script>

相关问题