The error validation works if there is only one instance of .item however when I duplicate the item and try to validate the input, the inputError function seems to run on every instance instead of just the one being validated.
How do I run the validate function on the only the inputs inside of each .item?
$(document).ready(function() {
var $items = $(".item");
$items.each(function() {
var $input = $(this).find(".input");
var inputCheck = function() {
var errorList = $("ul.errorMessages", $items);
var inputError = function() {
errorList.empty();
$items.find(":invalid").each(function(index, node) {
var label = $(node).attr("name");
var message = node.validationMessage || "Invalid value.";
errorList
.show()
.append(
"<li><span>" + label + ": " + "</span>" + message + "</li>"
);
});
};
$("input[type=submit], button", $items).on("click", inputError);
};
inputCheck();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form">
<div class="item">
<div class="success"></div>
<ul class="errorMessages"></ul>
<label>
<input required class="input" name="first" type="text" placeholder="first">
</label>
<label>
<input required class="input" name="second" type="text" placeholder="second">
</label>
<button type="submit">Create</button>
</div>
<div class="item">
<div class="success"></div>
<ul class="errorMessages"></ul>
<label>
<input required class="input" name="first_2" type="text" placeholder="first">
</label>
<label>
<input required class="input" name="second_2" type="text" placeholder="second">
</label>
<button type="submit">Create</button>
</div>
</div>