具有重复值检查的多个输入

时间:2016-07-18 14:29:11

标签: javascript jquery html

我有一个用于创建输入标签的按钮。当用户单击“提交”按钮时,我想查找具有重复值的输入并将边框更改为红色。

我没有使用jquery validate plugin

HTML代码:

<form>
<table>
   <tr>
    <td><input type="text" name="text[]" id="1"> <button class="add">add</button></td>
   </tr>
</table>
<input type="submit" id="submit" value="check">
</form>

jQuery代码:

// add input
var i = 2;

$('.add').click(function(e){
  e.preventDefault();
  $('table').append("<tr><td><input type="text" name="text[]" id="'+i+'"> <button class="add"></td></tr>");
  i++;
});

$('#submit').click(function(){
  // I do not know how to write ...
});

2 个答案:

答案 0 :(得分:3)

这是你想要的

   $('#submit').click(function () {
        var valid = true;

        $.each($('input[type="text"]'), function (index1, item1) {

            $.each($('input[type="text"]').not(this), function (index2, item2) {

                if ($(item1).val() == $(item2).val()) {
                    $(item1).css("border-color", "red");
                    valid = false;
                }

            });
        });

        return valid;
    });

答案 1 :(得分:2)

如果有人在此之后,有大量输入,并且关注效率,则会产生相同的结果(除第一次出现之外的重复标记):

$('#submit').click(function(){
  var values = []; //list of different values
  $('table input:text').each(
    function() {
      if (values.indexOf(this.value) >= 0) { //if this value is already in the list, marks
        $(this).css("border-color", "red");
      } else {
        $(this).css("border-color", ""); //clears since last check
        values.push(this.value); //insert new value in the list
      }
    }
  );
});

小提琴:

https://jsfiddle.net/4s82L4vg/

相关问题