jQuery根据下拉菜单中选择的数字动态创建输入字段? [英] jQuery dynamic creation of input fields based on the number selected in a dropdown menu?

查看:136
本文介绍了jQuery根据下拉菜单中选择的数字动态创建输入字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在努力完成一些这样的事情:

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

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

但是...我想显示一个下拉选择字段,值为1到20,并且取决于在该字段中选择哪个值,我将显示给用户填写多少个输入字段(当然不刷新)。

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).

所以,如果我在下拉框中选择4(最初没有显示输入字段,默认值应该是0),在它的下面有4行输入字段,名称&应该创建电子邮件,所有这些都是唯一的标识符(用于存储到mysql中)。

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.

提前感谢

推荐答案

所有您需要做的是找出当用户更改下拉列表时选择的号码,然后循环该号码,为每次迭代创建两个输入字段。

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

这篇关于jQuery根据下拉菜单中选择的数字动态创建输入字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆