Hi. so i have a div/form like this:

957d3e17b3579941c6bf92e594745d43

depending on the drop down value chosen that number of forms will appear like if value 2 chosen then 2 forms will appear if 4 then 4. the code is this:

$("select[name=children]").on("change", function(){
   var num_forms = $(this).val();
   var form = div.clone();
   var target = $("#the-child-form");
   for(var i = 0; i < num_forms; i++)
   {
     var clones = form.clone();
     clones.show();
     clones.prependTo(target);
   }
});

the thing with the code is that say for example value 1 was chosen by accident but u wanted to choose 2 so now u choose 2 but instead of 2 forms u get 3 forms. is there a way to go around that, a different apporach to the code? TIA!

As i understand your requirement you need to clear html before injecting new clone. i am not sure but just test your code in my way. hope this helps you.

<html>
<head>
  <script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
</head>
<body>
  <div style="width:4%;float:left;">
    <select name="children" id="children">
        <option value='1'>2</option>
        <option value='4'>4</option>
    </select>
  </div>     
   <div style="width:500px;float:left;">
    <div id="formtobeclone" style="float:left;">
        <input type="text" name="hello" id="hello">
    </div>
  </div>
  <div id="the-child-form"></div>
</body>
<script type="text/javascript">
  $("select[name=children]").on("change", function(){
   var num_forms = $(this).val();
   var form = $("#formtobeclone").clone();
   $("#the-child-form").html('');
   var target = $("#the-child-form");
   for(var i = 0; i < num_forms; i++)
   {
     var clones = form.clone();
     clones.show();
     clones.prependTo(target);
   }
});
</script>
</html>
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.