JSFiddle - React, Tailwind, and code Playground
HTML
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/jquery.validate.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jquery.validate/1.15.0/additional-methods.min.js"></script>
<form>
<fieldset>
<label></label><br>
<input name="file" type="file" accept=".jpg,.jpeg,.png" required />
<br>
<input type="submit" />
</fieldset>
</form>
<button>
add form
</button>
CSS
form {
border: 1px solid blue;
padding: 10px;
margin: 10px;
}
JavaScript
// maximum number of `form` elements which `document` should contain
var n = 4;
// display `form` index
function handleLabel() {
$("label").html(function(index, html) {
return "form #" + index
})
}
handleLabel();
function processFile() {
// preview uploaded image
$("<img>", {src: URL.createObjectURL(this.files[0])})
.insertAfter(this.nextElementSibling).after("<br>");
}
// handle file upload; delegate event to `document`
$(document).on("change", ":file", processFile);
// append cloned `form` to page
$("button").on("click", function() {
// if less than `n` forms
if ($("form").length < 4) {
// copy last `form` `.outerHTML` instead of using `.clone()`
$($("form:last")[0].outerHTML)
// remove `img` from `html`
.find("img").remove().end()
.insertAfter("form:last");
// update `form` `label` elements
handleLabel();
} else {
// detach `click` event from `button`
// when four `form` elements exist in `document`
$(this).off("click")
}
});
$(document).on("submit", "form", function(e) {
var img = $(this).find("img")[0];
if (img.naturalWidth < 600
|| img.naturalHeight < 400) {
e.preventDefault();
this.reset();
alert("invalid img width or height")
}
})