Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
275 views
in Technique[技术] by (71.8m points)

javascript - How to repeat the form data according to integer value get from the select box.?

How can form elements be repeated as many times as chosen by (the value of a) select box? I tried to get the value from the select box and based on that integer value, the form should be repeated. For example in select box, selecting 2 means the form should display 2 times. My html code is:

<select id="sel" class="sel">
<?php
$v=1; 
while($v<=10){
    ?>      
<option value="$v"> <?php echo $v; ?></option>
<?php $v++; } ?></select>
<button class="add_field_button">Add More Fields</button>
<div>name:<input type="text" name="mytext[]"></div>
</div>
<div id="inrlog" style="display:none;">
   <div>name:<input type="text" name="selname"></div>
 </div>

and my Javascript is:

 $(document).ready(function() {
var e = document.getElementById("sel");




$("#sel").select(function(){

   $("#sel").click(function(){
    $("#inrlog").show("slow");
});

});
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Attach an event listener to select and as per the value of the select input, con-cat input field to be appended and .append() in the container.

You can do this using for-loop

 $(document).ready(function() {
   $("#sel").on('change', function() {
     var counter = parseInt(this.value, 10);
     var html = '<div>name:<input type="text" name="selname">
  </div>';
     var str = "";
     for (var i = 0; i < counter; i++) {
       str += html;
     }
     $("#inrlog").empty().append(str);
   })
 });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div>
  <select id="sel" class="sel">
    <option value="1">1</option>
    <option value="2">2</option>
  </select>
  <button class="add_field_button">Add More Fields</button>
  <div>name:
    <input type="text" name="mytext[]">
  </div>
</div>
<div id="inrlog">
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...