You already have an answer that suits you in terms of solution, but it is always important to realize our mistakes so that we can evolve and not commit them in the future.
This is your Javascript code:
$("#qtdLote").on("change",function(){
var num=parseInt($(this).val());
for(var i=1;i<=num;i++){
$("#area").append("<div> Div "+i+"</div>");
}
});
Actually, it's very close to being as you intended. The first problem comes in de facto html, because $("#area")
does not hit the element you should because you defined it with #
more:
<div id="#area" ></div>
<!-- ^ -->
Removing #
to get id="area"
already fills the elements, according to what you select. But it ends up not cleaning up the previous ones every time you choose another option. You can do this by adding $("#area").html('');
before for
.
The only thing that is missing is to run the code barely starts, which can only do one more instruction, after the code it already has:
$("#qtdLote").trigger("change");
The trigger
programmatically forces the event passed as a parameter, in this case change
, as if it had been the user to do so.
See your code with these 3 small changes working:
$("#qtdLote").on("change",function(){
var num=parseInt($(this).val());
$("#area").html(''); //limpar antes de gerar
for(var i=1;i<=num;i++){
$("#area").append("<div> Div "+i+"</div>");
}
});
$("#qtdLote").trigger("change"); //forçar o trigger para quando abre a página
div{ border:1px solid #000; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><label>Escolha</label><selectid="qtdLote">
<option>1</option>
<option>2</option>
<option>3</option>
</select>
<div id="area" ></div> <!-- id corrigido-->