【问题标题】:Javascript New Input Field With Button and html带有按钮和 html 的 Javascript 新输入字段
【发布时间】:2015-11-20 12:35:27
【问题描述】:

我已经创建了这部分代码。每当按下按钮时,都会在表单中添加一个新的输入论坛字段。如何每次在字段旁边添加文本和数字(从 3 开始)? 例如:选项1:输入类型字段 选项 2:输入类型字段 选项 3:输入类型字段 等等

<SCRIPT language="javascript"> function add() {
//Create an input type dynamically.
var element = document.createElement("input");

//Assign different attributes to the element.
element.setAttribute("type", 'text');
element.setAttribute("value", '');
element.setAttribute("name", 'text[]');


var foo = document.getElementById("fooBar");
//Append the element in page (in span).
foo.appendChild(element);

}
</SCRIPT>

以上部分代码被以下人员使用(仅供参考):

<b>Option 1:</b> <input type="text" name="text[]" /><br />
<b>Option 2:</b> <input type="text" name="text[]" />
<input type="button" value="Add Option" onclick="add()"/>
<span id="fooBar"></span>

提前致谢! :)

【问题讨论】:

    标签: javascript html forms button


    【解决方案1】:
    var temp = 3;
    
    function add() {
    var element = document.createElement("input");
    var span = document.createElement("span");
        span.innerHTML = "Option "+temp;
    //Assign different attributes to the element.
     element.setAttribute("type", 'text');
     element.setAttribute("value", '');
     element.setAttribute("name", 'text[]');
    
    
     var foo = document.getElementById("fooBar");
    
      foo.appendChild(span);
      foo.appendChild(element);
    
    temp++;
    }
    

    【讨论】:

      【解决方案2】:

       var optionCount = 3;
      
       function add() {
         //Create an input type dynamically.
         var element = document.createElement("input");
         var label = document.createElement("label");
         label.innerHTML = "Option " + optionCount++ +":"
           //Assign different attributes to the element.
         element.setAttribute("type", 'text');
         element.setAttribute("value", '');
         element.setAttribute("name", 'text[]');
      
      
         var foo = document.getElementById("fooBar");
         //Append the element in page (in span).
         foo.appendChild(label);
         foo.appendChild(element);
      
       }
      <b>Option 1:</b> 
      <input type="text" name="text[]" />
      <br />
      <b>Option 2:</b> 
      <input type="text" name="text[]" />
      <input type="button" value="Add Option" onclick="add()" />
      <span id="fooBar"></span>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-02-04
        • 2012-06-14
        • 1970-01-01
        • 1970-01-01
        • 2016-10-31
        • 1970-01-01
        • 1970-01-01
        • 2017-09-09
        相关资源
        最近更新 更多