英文:
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("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 htmlpage using
<script src="script.js"> </script>
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:
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
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;
}
<!-- language: lang-html -->
<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>
<!-- end snippet -->
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-html -->
<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>
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论