JSFiddle - React, Tailwind, and code Playground
by Glink
HTML
<!-- <p>Name: <input type="file" id="test"></p>
<button id="file_button">Show Value</button>-->
<form id="prd" method="POST" enctype="multipart/form-data" action="javascript:alert('Enviado!');">
<div id="dynamicInput">
Foto<br><input type="file" class="test" name="myInputs[]">
</div>
<input type="button" id="btn2" value="Add foto" ><br>
<input type="button" id="btn1" value="Remove foto" ><br>
<input name="trip" type="submit">
</form>
JavaScript
$(document).ready(function() {
var counter = 0;
var limit = 4;
$("#btn2").click(function() {
if (counter >= limit) {
var limite=limit+1;
alert("You have reached the limit of " + limite + " fotos");
} else {
counter++;
$("#dynamicInput").append("<div class='dynamicField' id='cf" + counter + "'>Foto <br><input class='test' type='file' name='myInputs[]'></div>");
}
});
$("#btn1").click(function(){
if(counter == 0){
alert("You have to send at least one foto");
}else{
$(".dynamicField").remove("#cf" + counter + " " );
counter--;
}
});
$("#prd").submit(function(e) {
var ver;
$('.test').each(function(i, obj) {
var file = $(this).val();
var ext = $(this).val().substr(($(this).val().lastIndexOf('.') + 1));
alert(file);
ver = verifica(ext, file);
if (ver == false) {
return ver;
}
});
if (ver == false) {
return false;
}
});
function verifica(ext, file) {
if (ext == "jpg" || ext == "png" || ext == "JPG" || ext == "jpeg") {
alert("Ficheiro: " + file + " Válido");
return true;
} else {
alert("Invalid file only files with extension. Jpeg,. Jpg or. Png are accepted.");
return false;
}
};
});