如何在HTML表单中的数字输入类型中仅接受唯一值?

huangapple go评论74阅读模式
英文:

How to only accept unique values in a number input type in a form in html?

问题

I have a form with number input types, and I have limited responses to be between 1 and 14. However, I want to make the user input only unique numbers between 1 and 14. For example, if they put "2" for three different input boxes, I want a warning to pop up and not let them submit until they fix that.

我有一个带有数字输入类型的表单,我限制了响应在1到14之间。然而,我希望用户只能输入1到14之间的唯一数字。例如,如果他们在三个不同的输入框中输入"2",我希望出现警告,并且不允许他们提交,直到他们修复了这个问题。

Someone helped me and gave me this, however it does not seem to work. Am I not using it properly?

有人帮助了我,给了我这个代码,但似乎不起作用。我是不是没有正确使用它?

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;
}

This is how my number inputs look.

这是我的数字输入看起来的样子。

<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>

I have included the javascript into my html page using

我已经将javascript包含到我的HTML页面中,使用了

<script src="script.js"> </script>

Am I implementing the code wrong into my HTML? Does it actually not work? Please help, thank you!

我是不是在HTML中错误地实现了这段代码?它实际上是不是不起作用?请帮忙,谢谢!

英文:

I have a form with number input types, and I have limited responses to be between 1 and 14. However, I want to make the user input only unique numbers between 1 and 14. For example, if they put "2" for three different input boxes, I want a warning to pop up and not let them submit until they fix that.

Someone helped me and gave me this, however it does not seem to work. Am I not using it properly?

document.getElementById(&quot;formName&quot;).addEventListener(&quot;submit&quot;, function(event) {
  // Here you get all unique-number inputs.
  var inputs = Array.from(document.getElementsByClassName(&#39;unique&#39;));
  
  // 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(&quot;Please ensure all numbers are unique.&quot;);
  }
});

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

  return false;
}

This is how my number inputs look.

&lt;label&gt;&lt;input type=&quot;number&quot; name=&quot;num&quot; min=&quot;1&quot; max=&quot;14&quot; autocomplete=&quot;off&quot; oninvalid=&quot;this.setCustomValidity(&#39;Please enter a number between 1 and 14&#39;)&quot; oninput=&quot;this.setCustomValidity(&#39;&#39;)&quot; class=&quot;unique&quot;&gt; &lt;span&gt;Mark Twain&lt;/span&gt;&lt;/label&gt;
&lt;br&gt;

I have included the javascript into my htmlpage using
&lt;script src=&quot;script.js&quot;&gt; &lt;/script&gt;

Am I implementing the code wrong into my html? Does it actually not work? Please help, thank you!

答案1

得分: 1

以下是翻译好的部分:

"By my benchmarking (below the answer) using Set is the fastest way to handle unique values:" -> "根据我的基准测试(见答案下方),使用 Set 是处理唯一值的最快方法:"

"document.getElementById("formName").addEventListener("submit", e => {" -> "document.getElementById("formName").addEventListener("submit", e => {"

"const values = Array.from(e.target.querySelectorAll('.unique'))\n.map(input => parseInt(input.value)).filter(num => num === num);" -> "const values = Array.from(e.target.querySelectorAll('.unique'))\n.map(input => parseInt(input.value)).filter(num => num === num);"

"try {" -> "try {"

"if (!isUnique(values)) {" -> "if (!isUnique(values)) {"

"throw new Error("Please ensure all numbers are unique.");" -> "throw new Error("请确保所有数字都是唯一的。");"

"alert(err.message);" -> "alert(err.message);"

"e.preventDefault();" -> "e.preventDefault();"

"function isUnique(arr) {" -> "function isUnique(arr) {"

"const set = new Set;" -> "const set = new Set;"

"for (let i = 0; i < arr.length; i++) {" -> "for (let i = 0; i < arr.length; i++) {"

"const val = arr[i];" -> "const val = arr[i];"

"if (set.has(val)) {" -> "if (set.has(val)) {"

"return false;" -> "return false;"

"set.add(val);" -> "set.add(val);"

"return true;" -> "return true;"

"<form id="formName">" -> "<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>" -> "<label><input type="number" name="num" min="1" max="14" autocomplete="off" oninvalid="this.setCustomValidity('请输入1到14之间的数字。')" oninput="this.setCustomValidity('')" class="unique"> <span>马克·吐温</span></label>"

"<br>" -> "<br>"

"<button>Submit</button>" -> "<button>提交</button>"

"</form>" -> "</form>"

"<body></body>" -> "<body></body>"

"<script name="benchmark" data-count="1">" -> "<script name="benchmark" data-count="1">"

"const count = 1000000;" -> "const count = 1000000;"

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

"function isUnique(arr) {" -> "function isUnique(arr) {"

"const set = new Set;" -> "const set = new Set;"

"for (let i = 0; i < arr.length; i++) {" -> "for (let i = 0; i < arr.length; i++) {"

"const val = arr[i];" -> "const val = arr[i];"

"if (set.has(val)) {" -> "if (set.has(val)) {"

"return false;" -> "return false;"

"set.add(val);" -> "set.add(val);"

"return true;" -> "return true;"

"function isUnique2(arr) {" -> "function isUnique2(arr) {"

"const set = {};" -> "const set = {};"

"for (let i = 0; i < arr.length; i++) {" -> "for (let i = 0; i < arr.length; i++) {"

"const val = arr[i];" -> "const val = arr[i];"

"if (val in set) {" -> "if (val in set) {"

"return false;" -> "return false;"

"set[val] = true;" -> "set[val] = true;"

"// @benchmark using Set" -> "// 使用 Set 进行基准测试"

"isUnique(arr);" -> "isUnique(arr);"

"// @benchmark using object" -> "// 使用对象进行基准测试"

"isUnique2(arr);" -> "isUnique2(arr);"

"</script>" -> "</script>"

"1: https://i.stack.imgur.com/JZ942.png" -> "1: https://i.stack.imgur.com/JZ942.png"

英文:

By my benchmarking (below the answer) using Set is the fastest way to handle unique values:

如何在HTML表单中的数字输入类型中仅接受唯一值?
<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

document.getElementById(&quot;formName&quot;).addEventListener(&quot;submit&quot;, e =&gt; {
  
  const values = Array.from(e.target.querySelectorAll(&#39;.unique&#39;))
    .map(input =&gt; parseInt(input.value)).filter(num =&gt; num === num);

  try {

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

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

<!-- language: lang-html -->

&lt;form id=&quot;formName&quot;&gt;
&lt;label&gt;&lt;input type=&quot;number&quot; name=&quot;num&quot; min=&quot;1&quot; max=&quot;14&quot; autocomplete=&quot;off&quot; oninvalid=&quot;this.setCustomValidity(&#39;Please enter a number between 1 and 14&#39;)&quot; oninput=&quot;this.setCustomValidity(&#39;&#39;)&quot; class=&quot;unique&quot;&gt; &lt;span&gt;Mark Twain&lt;/span&gt;&lt;/label&gt;
&lt;br&gt;&lt;label&gt;&lt;input type=&quot;number&quot; name=&quot;num&quot; min=&quot;1&quot; max=&quot;14&quot; autocomplete=&quot;off&quot; oninvalid=&quot;this.setCustomValidity(&#39;Please enter a number between 1 and 14&#39;)&quot; oninput=&quot;this.setCustomValidity(&#39;&#39;)&quot; class=&quot;unique&quot;&gt; &lt;span&gt;Mark Twain&lt;/span&gt;&lt;/label&gt;
&lt;br&gt;&lt;label&gt;&lt;input type=&quot;number&quot; name=&quot;num&quot; min=&quot;1&quot; max=&quot;14&quot; autocomplete=&quot;off&quot; oninvalid=&quot;this.setCustomValidity(&#39;Please enter a number between 1 and 14&#39;)&quot; oninput=&quot;this.setCustomValidity(&#39;&#39;)&quot; class=&quot;unique&quot;&gt; &lt;span&gt;Mark Twain&lt;/span&gt;&lt;/label&gt;
&lt;br&gt;&lt;label&gt;&lt;input type=&quot;number&quot; name=&quot;num&quot; min=&quot;1&quot; max=&quot;14&quot; autocomplete=&quot;off&quot; oninvalid=&quot;this.setCustomValidity(&#39;Please enter a number between 1 and 14&#39;)&quot; oninput=&quot;this.setCustomValidity(&#39;&#39;)&quot; class=&quot;unique&quot;&gt; &lt;span&gt;Mark Twain&lt;/span&gt;&lt;/label&gt;
&lt;br&gt;&lt;label&gt;&lt;input type=&quot;number&quot; name=&quot;num&quot; min=&quot;1&quot; max=&quot;14&quot; autocomplete=&quot;off&quot; oninvalid=&quot;this.setCustomValidity(&#39;Please enter a number between 1 and 14&#39;)&quot; oninput=&quot;this.setCustomValidity(&#39;&#39;)&quot; class=&quot;unique&quot;&gt; &lt;span&gt;Mark Twain&lt;/span&gt;&lt;/label&gt;
&lt;br&gt;
&lt;button&gt;Submit&lt;/button&gt;
&lt;/form&gt;

<!-- end snippet -->

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-html -->

&lt;body&gt;&lt;/body&gt;
&lt;script name=&quot;benchmark&quot; data-count=&quot;1&quot;&gt;

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

    function isUnique(arr) {
        const set = new Set;
        for (let i = 0; i &lt; 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 &lt; 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);

&lt;/script&gt;
&lt;script src=&quot;https://cdn.jsdelivr.net/gh/silentmantra/benchmark/loader.js&quot;&gt;&lt;/script&gt;

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月13日 00:56:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/76458794.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定