1
I’m trying to get when the user enters a certain number in a <input>
be created the same amount of fields, I tried to do in a way I found here, but I could not make it create the number of fields I type, only creates a label, nor the input appears, follows below the code:
<div class="form-group" id="vem">
</div>
<input type="number" class="form-control round-input" name="numero_parc" required="required" min="1" id="par">
$(document).ready(function() {
var max_fields = 10;
var wrapper = $("#vem");
var add_button = $("#par");
$(add_button).change(function(e) {
e.preventDefault();
var length = wrapper.find("input:text#textAdded").length;
$(wrapper).append('<label class="col-sm-2 col-sm-2 control-label">' + (length+1) +'</label><div class="col-md-5"><input type="date" class="form-control round-input" id="textAdded" name="num' + (length+1) + '"></div>');
});
});
for:
function criaCampos(){
var qtd = document.getElementById('par').value;
if (qtd > 1) {
for(var i=0; i < qtd; i++){
document.getElementById('vem').innerHTML = '<label class="col-sm-2 col-sm-2 control-label">1º</label><div class="col-md-5"><input type="date" class="form-control round-input" name="'+ qtd[i]+'"></div>';
}
}
}
You forgot to close the input div
– bfavaretto
It still doesn’t work
– R.Gasparin
Yes, there are other problems. The loop itself is missing
– bfavaretto
Just try add_button.change(Function(){ ... });
– Ricardo
Yeah, I don’t know how to build this loop, or if there was a way through this code to create the number of fields the user chooses.
– R.Gasparin
Pro loop you can use "for". Read this: https://www.w3schools.com/js/js_loop_for.asp
– Ricardo
I tried to do a for the way I entered the question now, but it didn’t work. So I found this second code, which sounded better, but it still doesn’t work the way I need it
– R.Gasparin
document.getElementById('vem').innerHTML += ...
– bfavaretto
What is going wrong is when, for example, I type 3 for the number of fields, but then the for creates two and stops, and still the second is created only the label, without input
– R.Gasparin
https://jsfiddle.net/ht6qgd83/
– Don't Panic