jQuery dynamic creation of input fields based on t

2019-01-29 06:03发布

I am trying to accomplish something along the lines of this:

http://devblog.jasonhuck.com/assets/infiniteformrows.html

But... I want to display a dropdown select field, with values 1 to 20, and depending on which value gets selected in that field that's how many input fields I will display to a user to fill out on the page (without refreshing, of course).

So, if I select 4 in the dropdown box (initially there are no input fields shown, as the default should be 0), right underneath it 4 lines of input fields for Name & Email should be created, all with unique identifiers and such (for storing into mysql).

And for the life of me, I can't find any examples of anyone doing just that, so I thought I'd present a little challenge here instead.

Thanks in advance!

3条回答
混吃等死
2楼-- · 2019-01-29 06:13

This will insert a text box after the select on the page. It will fire each time the number is changed.

var idFun = 0;
$('select').change(function() { 
  var end=$(this).val(); 
  for (var i=0;i<end;i++) {
    $('<div><input id="fun' + (idFun++) + ' type="text" ></div>').appendTo($('#myinputs'));

  }
});

HTML:

<select>
  ... 1 to 20 here
</select>
<div id="myinputs"></div>

Hope this helps.

查看更多
一夜七次
3楼-- · 2019-01-29 06:13

The real sollution:

<script type="text/javascript">

    $(document).ready(function() {

        $("#AantalAntw").change(function() {
            var htmlString = "";
            var len = $("#AantalAntw").val();
            for (var i = 0; i < len; i++) {
                htmlString += "<input type='text' class='email'>";
                htmlString += "<input type='text' class='name'>";
            }
            alert(htmlString);
            $("#antwblok").html(htmlString);
        });
    });

</script>
查看更多
Juvenile、少年°
4楼-- · 2019-01-29 06:24

All you need to do, is find out which number is selected when the user changes the dropdown, then loop through that number, creating two input fields for each iteration.

$("#selectBox").change(function() {
  var htmlString = "";
  var len = $("options:selected", this).val();
  for (var i = 0; i < len; i++) {
    htmlString += "<input type='text' class='email'>";
    htmlString += "<input type='text' class='name'>";
  }
  $("#outputArea").html(htmlString);
}

And you might even want to make it smarter, so it checks how many input fields you already have, and then make only as many as needed, or remove some. That way, it'll be a bit faster (:

查看更多
登录 后发表回答