Each time I click the create button I want to run inputCheck and if there are no errors (and the errorList is empty) then run the swal function to confirm the post. If there are errors, then don't run the alert.
$(".btn--post", $this).on("click", function() {
inputError();
if (errorList.length == 0) {
swal({})
}
});
I only want to run the swal function if there are no errors in errorList. My current markup however isn't running the swal if the errorList is empty.
$(document).ready(function() {
var $item = $(".post__item");
$item.each(function() {
var $input = $(this).find(".input");
var $this = $(this);
var inputCheck = function() {
var errorList = $("div.details__error", $this);
var inputError = function() {
errorList.empty();
$this.find(":required:invalid").each(function(index, node) {
var label = $(node).attr("name");
var message = node.validationMessage || "Invalid value.";
errorList
.show()
.append(
"<div><span>" + label + ": " + "</span>" + message + "</div>"
);
});
};
$(".btn--post", $this).on("click", function() {
inputError();
if (errorList.length == 0) {
swal({
title: "Create Post?",
text: "You won't be able to make changes to your post later.",
confirmButtonText: "Post",
confirmButtonColor: "#6064e6",
cancelButtonColor: "#d33",
reverseButtons: true,
showCancelButton: true
}).then((result) => {
if (result.value) {
/*Post Item*/
} else if (result.dismiss === "cancel") {
/* swal("Cancelled", "Your stay here :)", "error");*/
}
});
}
});
};
inputCheck();
});
});
.details__icon {
height: 26px;
border: 1px solid
}
.form {
display: flex;
flex-direction: column;
}
.post__item {
border: 2px solid;
height: 120px
}
.post__item label {
height: 146px;
background: blue;
margin: 12px;
padding: 12px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.2.0/sweetalert2.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/limonte-sweetalert2/7.2.0/sweetalert2.all.min.js"></script>
<div>
<div class="post__item">
<div class="details__icon"></div>
<div class="details__error"></div>
<label>
<textarea required class="input" name="first" type="text" placeholder="first"></textarea>
</label>
<label>
<input required class="input" name="second" type="text" placeholder="second">
</label>
<button class="btn--post">Create</button>
</div>
<div class="post__item">
<div class="details__icon"></div>
<div class="details__error"></div>
<label>
<textarea required class="input" name="first" type="text" placeholder="first"></textarea>
</label>
<label>
<input required class="input" name="second" type="text" placeholder="second">
</label>
<button class="btn--post">Create</button>
</div>
</div>