我如何动态创建输入框? [英] How would I dynamically create input boxes on the fly?

查看:160
本文介绍了我如何动态创建输入框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用HTML下拉框的值,并创建下面的输入框。我希望我可以在飞行中实现这一点。此外,如果值更改,它应该适当地添加或删除。



我需要什么编程语言?我正在整个网站使用PHP。

解决方案

下面是一个使用jQuery实现目标的例子:



假设你有以下html:

 < div> 
< select id =input_count>
< option value =1> 1输入< / option>
< option value =2> 2个输入< / option>
< option value =3> 3个输入< / option>
< / select>
< div>
< div id =inputs> < / DIV>

这是您的任务的js代码:



($)$($)$($($)$($)$($) :selected);
var selectedValue = selectedOption.val();

var targetDiv = $(#inputs);
targetDiv.html();
for(var i = 0; i< selectedValue; i ++){
targetDiv.append($(< input />));
}
} );

您可以简化此代码,如下所示:



< pre $ $('#input_count')。change(function(){
var selectedValue = $(this).val();

var对于(var i = 0; i< selectedValue; i ++){
targetDiv.append($(< input / >));
}
});

这是一个工作的小提琴示例: http://jsfiddle.net/melih/VnRBm/



您可以阅读更多关于jQuery的信息: http://jquery.com/


I want to use the value of a HTML dropdown box and create that number of input boxes underneath. I'm hoping I can achieve this on the fly. Also if the value changes it should add or remove appropriately.

What programming language would I need to do this in? I'm using PHP for the overall website.

解决方案

Here is an example that uses jQuery to achieve your goals:

Assume you have following html:

  <div>
    <select id="input_count">
      <option value="1">1 input</option>
      <option value="2">2 inputs</option>
      <option value="3">3 inputs</option>
    </select>
  <div>
  <div id="inputs"> </div>

And this is the js code for your task:

  $('#input_count').change(function() {
      var selectObj = $(this);
      var selectedOption = selectObj.find(":selected");
      var selectedValue = selectedOption.val();

      var targetDiv = $("#inputs");
      targetDiv.html("");
      for(var i = 0; i < selectedValue; i++) {
        targetDiv.append($("<input />"));
      }
  });

You can simplify this code as follows:

  $('#input_count').change(function() {
      var selectedValue = $(this).val();

      var targetDiv = $("#inputs").html("");
      for(var i = 0; i < selectedValue; i++) {
        targetDiv.append($("<input />"));
      }
  });

Here is a working fiddle example: http://jsfiddle.net/melih/VnRBm/

You can read more about jQuery: http://jquery.com/

这篇关于我如何动态创建输入框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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