vulkan vulkan - 4 months ago 12
jQuery Question

Multiple inputs with duplicate value check

I have a button to create input tags. When user click submit button I want to find inputs with duplicate values and change border to red.

I'm not using jquery validate plugin

html code:

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

// 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 ...
});

Answer

Here is what you want

   $('#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;
    });