简体   繁体   English

Javascript添加动态输入字段

[英]Javascript Add Dynamic Input Field

I'm not good with Javascript at all, so I come here to seek assistance. 我对Javascript一点都不好,所以我来这里寻求帮助。

What I have is a form, with a link that says "Add additional URL field". 我所拥有的是一个表单,其中的链接显示“添加其他URL字段”。 I want it so when a user clicks that, it will populate an additional field underneath the default url field, with a unique input name, such as url_input1, and if they click it again to add another url input, the name of that input would be url_input2, etc. 我想要它,所以当用户点击它时,它将填充默认url字段下的附加字段,具有唯一的输入名称,例如url_input1,如果他们再次单击它以添加另一个url输入,则该输入的名称将是url_input2等

How can I do this with Javascript? 我怎么能用Javascript做到这一点?

This is a perfect job for JS library like jQuery. 对于像jQuery这样的JS库来说,这是一个完美的工作。 For a jQuery example implementation of this, see this . 有关此jQuery示例实现,请参阅此内容

if you want to handcraft this using pure JavaScript and DOM manipulation, you have 2 choices: 如果你想使用纯JavaScript和DOM操作来手工制作,你有两个选择:

  1. You can do createElement and combine that with either appendChild (see this or this ) or insertBefore (see this or this ) depending where your insert point is. 您可以执行createElement并将其与appendChild(请参阅thisthis )或insertBefore(请参阅thisthis )组合,具体取决于插入点的位置。 (as suggested by Sonic Soul) (按照Sonic Soul的建议)
  2. Use innerHTML and add the control by passing the HTML of control into it, which is quite similar to the jQuery approach that is in my spike. 使用innerHTML并通过将控件的HTML传递给它来添加控件,这与我的spike中的jQuery方法非常相似。 (as described by Joshua) (如约书亚所述)

Option 1 is slower than Option 2. 选项1比选项2慢。

Personally, I'll use jQuery since it will abstract some of DOM implementation that might cause some cross browser issues and simply because it's nicer and very powerful for doing stuffs like this. 就个人而言,我将使用jQuery,因为它将抽象一些可能导致一些跨浏览器问题的DOM实现,并且仅仅因为它对于做这样的事情更好,更强大。

look at createElement http://www.adp-gmbh.ch/web/js/elements/createelement.html 看看createElement http://www.adp-gmbh.ch/web/js/elements/createelement.html

var someCounter = 0;
...
var i  = document.createElement('input');
i.type = 'text';
i.id = 'myInput_' + someCounter++;

as for id, you can simply append a counter to whatever id name you wish to provide (see above) 对于id,你可以简单地将一个计数器附加到你想提供的任何id名称上(见上文)

Alternatively, I would say you could just write the HTML from scratch with javascript. 或者,我会说你可以用javascript从头开始编写HTML。 I've always had problems with document.createElement, so an alternative would be: 我总是遇到document.createElement的问题,所以另一种方法是:

function get_parent_add_input() {
var parent_element = this.parentNode;// here, we get the parent node
var current_innerHTML = String(parent_element.innerHTML);
var new_input_html = '<input type="text" name="inputs[]" />';
parent_element.innerHTML = current_innerHTML + new_input_html;
}

This function would get the parent element of the text input in question, thus allowing you to add to its innerHTML. 此函数将获取有问题的文本输入的父元素,从而允许您添加到其innerHTML。

As for adding 1 to the id each time, you have no need. 至于每次为id添加1,你没有必要。 If you're capturing the form input via PHP, you would simply use $_POST['inputs'] , which would return an array of the values of all inputs with the name inputs . 如果您通过PHP捕获表单输入,则只需使用$_POST['inputs'] ,它将返回名称为input的所有输入值的数组。

this example alow you to add and remove dynamic inputs 这个例子让你添加和删除动态输入

try something like this : 尝试这样的事情:

   $(document).ready(function() {

    var MaxInputs       = 8; //maximum input boxes allowed
   var InputsWrapper   = $("#InputsWrapper"); //Input boxes wrapper ID
   var AddButton       = $("#AddMoreFileBox"); //Add button ID

  var x = InputsWrapper.length; //initlal text box count
  var FieldCount=1; //to keep track of text box added

  $(AddButton).click(function (e)  //on add input button click
 {
    if(x <= MaxInputs) //max input box allowed
    {
            FieldCount++; //text box added increment
           //add input box
        $(InputsWrapper).append('<div><input type="text" name="mytext[]"                            
         id="field_'+ FieldCount +'" value="Text '+ FieldCount +'"/><a href="#" class="removeclass">&times;</a></div>');
        x++; //text box increment
    }
  return false;
  });

 $("body").on("click",".removeclass", function(e){ //user click on remove text
    if( x > 1 ) {
            $(this).parent('div').remove(); //remove text box
                x--; //decrement textbox
            }
      return false;
})

});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM