首页 > 解决方案 > 防止用户在 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 代码中进行哪些更改,以便在输入重复代码时,应该出现警报消息“找到重复代码”。

标签: javascripthtmlinputalert

解决方案


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.


推荐阅读