javascript - 防止用户在 javascript 的文本输入中输入重复的条目
问题描述
我有一个 DOM,我想阻止用户在 html 文本输入中输入重复的条目。
上面的DOM不受用户控制。它是通过 php 来的。
此刻,我只专注于name="code[]".
这是我尝试过的:
$(function(){
$('input[name^="code"]').change(function() {
var $current = $(this);
$('input[name^="code"]').each(function() {
if ($(this).val() == $current.val())
{
alert('Duplicate code Found!');
}
});
});
});
问题陈述:
我想知道我应该在上面的 javascript 代码中进行哪些更改,以便在输入重复代码时,应该出现警报消息“找到重复代码”。
解决方案
you need to add an eventlistener to each item, not an eventlistener for all. Then count inputs with same value, if there's more than 1, it's a duplicate.
Also ignore not-filled inputs.
Check following snippet:
$('input[name*="code"]').each(function() {
$(this).change(function(){
let value = $(this).val();
let count = 0;
$('input[name*="code"]').each(function() {
if ($(this).val() != '' && $(this).val() == value) {
count++;
if (count > 1) alert('duplicate');
}
});
});
$(this).addClass('e');
});
$('#createInput').on('click', function(){
let newInput = document.createElement("input");
newInput.name = 'code[]';
newInput.type = 'text';
newInput.className = 'whatever';
$('#inputGroup').append(newInput);
// repeat the eventlistener again:
$('input[name*="code"]:not(.e').each(function() {
$(this).change(function(){
let value = $(this).val();
let count = 0;
$('input[name*="code"]').each(function() {
if ($(this).val() != '' && $(this).val() == value) {
count++;
if (count > 1) alert('duplicate');
}
});
});
$(this).addClass('e');
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="inputGroup">
<input name="code-1" type="text" class="whatever">
<input name="code-2" type="text" class="whatever2">
<input name="code-3" type="text" class="whatever3">
</div>
<input type="button" id="createInput" value="Add input">
Edit: now works with dynamically created elements. The class 'e' works as flag to not insert 2 event listeners to the same node element, otherwise they will run in cascade, provoking unwanted behaviour.
推荐阅读
- c# - asp.net mvc核心依赖注入构造函数参数
- javascript - React JS- 对配置文件的数据进行编码并将其传递给 Header 以进行 api 调用
- ios - 编译器无法在合理的时间内对该表达式进行类型检查;尝试将表达式分解为不同的子表达式
- internet-explorer - 使用 Protractor 框架的 Internet Explorer 中不显示元素
- php - 如何将 xml 解析为 docx 文件中的字符串
- ruby - 根据用户输入循环创建
- python - 如何提取 CSV 文件的特定行
- java - 桌面应用程序在最终用户计算机上无法正常工作,但在本地计算机上却可以
- google-app-maker - Google App Maker:以编程方式访问小部件的种类(组件的类名)
- javascript - javascript:正确获取来自不同类的函数调用的返回语句的值