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
735 views
in Technique[技术] by (71.8m points)

forms - jQuery dynamic creation of input fields based on the number selected in a dropdown menu?

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!

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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 (:


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

...