简体   繁体   English

如何创建<input type="“text”/">动态地

[英]How to create <input type=“text”/> dynamically

I want to create an input type text in my web form dynamically.我想在我的 web 表单中动态创建一个输入类型文本。 More specifically, I have a textfield where the user enters the number of desired text fields;更具体地说,我有一个文本字段,用户可以在其中输入所需文本字段的数量; I want the text fields to be generated dynamically in the same form.我希望以相同的形式动态生成文本字段。

How do I do that?我怎么做?

With JavaScript:使用 JavaScript:

var input = document.createElement("input");
input.type = "text";
input.className = "css-class-name"; // set the CSS class
container.appendChild(input); // put it into the DOM

Using Javascript, all you need is document.createElement and setAttribute .使用 Javascript,您只需要document.createElementsetAttribute

var input = document.createElement("input");
input.setAttribute('type', 'text');

Then you can use appendChild to append the created element to the desired parent element.然后您可以使用appendChild将创建的元素附加到所需的父元素。

var parent = document.getElementById("parentDiv");
parent.appendChild(input);

To create number of input fields given by the user创建用户提供的输入字段数量


  1. Get the number of text fields from the user and assign it to a variable.从用户那里获取文本字段的数量并将其分配给一个变量。

    var no = document.getElementById("idname").value


  1. To create input fields, use createElement method and specify element name ie "input" as parameter like below and assign it to a variable.要创建输入字段,请使用createElement方法并指定元素名称,即“输入”作为参数,如下所示,并将其分配给变量。

    var textfield = document.createElement("input");


  1. Then assign necessary attributes to the variable.然后为变量分配必要的属性。

    textfield.type = "text";

    textfield.value = "";


  1. At last append variable to the form element using appendChild method.最后使用appendChild方法将变量附加到表单元素。 so that the input element will be created in the form element itself.这样输入元素将在表单元素本身中创建。

    document.getElementById('form').appendChild(textfield);


  1. Loop the 2,3 and 4 step to create desired number of input elements given by the user inside the form element.循环 2,3 和 4 步骤以创建用户在表单元素内指定的所需数量的输入元素。

     for(var i=0;i<no;i++) { var textfield = document.createElement("input"); textfield.type = "text"; textfield.value = ""; document.getElementById('form').appendChild(textfield); }

Here's the complete code这是完整的代码

 function fun() { /*Getting the number of text fields*/ var no = document.getElementById("idname").value; /*Generating text fields dynamically in the same form itself*/ for(var i=0;i<no;i++) { var textfield = document.createElement("input"); textfield.type = "text"; textfield.value = ""; document.getElementById('form').appendChild(textfield); } }
 <form id="form"> <input type="type" id="idname" oninput="fun()" value=""> </form>

See this answer for a non JQuery solution.有关非 JQuery 解决方案,请参阅此答案。 Just helped me out!刚刚帮我解决了!

Adding input elements dynamically to form 动态添加输入元素到表单

Maybe the method document.createElement();也许方法document.createElement(); is what you're looking for.就是你要找的。

I think the following link will help you.我认为以下链接会对您有所帮助。 If you want to generate fields dynamically and also want to remove them on the same time you can get the help from here.如果您想动态生成字段并同时删除它们,您可以从这里获得帮助。 I had the same question, So i got the answer我有同样的问题,所以我得到了答案

$(function() {
        var scntDiv = $('#p_scents');
        var i = $('#p_scents p').size() + 1;

        $('#addScnt').live('click', function() {
                $('<p><label for="p_scnts"><input type="text" id="p_scnt" size="20" name="p_scnt_' + i +'" value="" placeholder="Input Value" /></label> <a href="#" id="remScnt">Remove</a></p>').appendTo(scntDiv);
                i++;
                return false;
        });

        $('#remScnt').live('click', function() { 
                if( i > 2  ) {
                        $(this).parents('p').remove();
                        i--;
                }
                return false;
        });
});

http://jsfiddle.net/jaredwilli/tZPg4/4/ http://jsfiddle.net/jaredwilli/tZPg4/4/

You could do something like this in a loop based on the number of text fields they enter.您可以根据他们输入的文本字段的数量在循环中执行类似的操作。

$('<input/>').attr({type:'text',name:'text'+i}).appendTo('#myform');

But for better performance I'd create all the html first and inject it into the DOM only once.但是为了获得更好的性能,我会先创建所有的 html 并将其注入 DOM 一次。

var count = 20;
var html = [];
while(count--) {
  html.push("<input type='text' name='name", count, "'>");
}
$('#myform').append(html.join(''));

Edit this example uses jQuery to append the html, but you could easily modify it to use innerHTML as well.编辑此示例使用 jQuery 附加 html,但您也可以轻松修改它以使用 innerHTML。

您可以使用createElement()方法来创建该文本框

The core idea of the solution is:解决方案的核心思想是:

  • create a new input element创建一个新的input元素
  • Add the type text添加类型text
  • append the element to the DOM将元素附加到 DOM

This can be done via this simple script:这可以通过这个简单的脚本来完成:

var input = document.createElement('input');
input.setAttribute('type', 'text');
document.getElementById('parent').appendChild(input);

Now the question is, how to render this process dynamic.现在的问题是,如何使这个过程动态化。 As stated in the question, there is another input where the user insert the number of input to generate.正如问题中所述,还有另一个输入,用户在其中插入要生成的输入数量。 This can be done as follows:这可以按如下方式完成:

 function renderInputs(el){ var n = el.value && parseInt(el.value, 10); if(isNaN(n)){ return; } var input; var parent = document.getElementById("parent"); cleanDiv(parent); for(var i=0; i<n; i++){ input = document.createElement('input'); input.setAttribute('type', 'text'); parent.appendChild(input); } } function cleanDiv(div){ div.innerHTML = ''; }
 Insert number of input to generate: </br> <input type="text" onchange="renderInputs(this)"/> <div id="parent"> Generated inputs: </div>

but usually adding just an input is not really usefull, it would be better to add a name to the input, so that it can be easily sent as a form.但通常只添加一个输入并不是很有用,最好为输入添加一个名称,以便它可以轻松地作为表单发送。 This snippet add also a name:此代码段还添加了一个名称:

 function renderInputs(el){ var n = el.value; var input, label; var parent = document.getElementById("parent"); cleanDiv(parent); el.value.split(',').forEach(function(name){ input = document.createElement('input'); input.setAttribute('type', 'text'); input.setAttribute('name', name); label = document.createElement('label'); label.setAttribute('for', name); label.innerText = name; parent.appendChild(label); parent.appendChild(input); parent.appendChild(document.createElement('br')); }); } function cleanDiv(div){ div.innerHTML = ''; }
 Insert the names, separated by comma, of the inputs to generate: </br> <input type="text" onchange="renderInputs(this)"/> <br> Generated inputs: </br> <div id="parent"> </div>

you can use ES6 back quits你可以使用 ES6 退出

 var inputs = [ `<input type='checkbox' id='chbox0' onclick='checkboxChecked(this);'> <input type='text' class='noteinputs0'id='note` + 0 + `' placeholder='task0'><button id='notebtn0' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 1 + `' placeholder='task1'><button class='notebuttons' id='notebtn1' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 2 + `' placeholder='task2'><button class='notebuttons' id='notebtn2' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 3 + `' placeholder='task3'><button class='notebuttons' id='notebtn3' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 4 + `' placeholder='task4'><button class='notebuttons' id='notebtn4' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 5 + `' placeholder='task5'><button class='notebuttons' id='notebtn5' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 6 + `' placeholder='task6'><button class='notebuttons' id='notebtn6' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 7 + `' placeholder='task7'><button class='notebuttons' id='notebtn7' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 8 + `' placeholder='task8'><button class='notebuttons' id='notebtn8' >creat</button>`, `<input type='text' class='noteinputs' id='note` + 9 + `' placeholder='task9'><button class='notebuttons' id='notebtn9' >creat</button>` ].sort().join(" "); document.querySelector('#hi').innerHTML += `<br>` +inputs;
 <div id="hi"></div>

  • Query and get the container DOM element查询并获取容器DOM元素

  • Create new element创建新元素

  • Put new element to document Tree将新元素放入文档 Tree

//Query some Dib region you Created
let container=document.querySelector("#CalculationInfo .row .t-Form-itemWrapper");
let input = document.createElement("input");

//create new Element  for apex
input.setAttribute("type","text");
input.setAttribute("size","30");
containter.appendChild(input); // put it into the DOM
<button id="add" onclick="add()">Add Element</button>

<div id="hostI"></div>

<template id="templateInput">
    <input type="text">
</template>

<script>
    function add() {

        // Using Template, element is created
        var templateInput = document.querySelector('#templateInput');
        var clone = document.importNode(templateInput.content, true);

        // The Element is added to document
        var hostI = document.querySelector('#hostI');
        hostI.appendChild(clone);
    }

</script>

HTML Templates are now the recommended standards to generate dynamic content. HTML 模板现在是生成动态内容的推荐标准。

Try this:尝试这个:

 function generateInputs(form, input) { x = input.value; for (y = 0; x > y; y++) { var element = document.createElement('input'); element.type = "text"; element.placeholder = "New Input"; form.appendChild(element); } }
 input { padding: 10px; margin: 10px; }
 <div id="input-form"> <input type="number" placeholder="Desired number of inputs..." onchange="generateInputs(document.getElementById('input-form'), this)" required><br> </div>

The code above, has a form with an input which accepts a number in it:上面的代码有一个表单,其中的输入接受一个数字:

<form id="input-form">
  <input type="number" placeholder="Desired number of inputs..." onchange="generateInputs(document.getElementById('input-form'), this)"><br>
</form>

The input runs a function onchange , meaning that when the user has entered a number and clicked submit, it run a function.输入运行一个函数onchange ,这意味着当用户输入一个数字并点击提交时,它运行一个函数。 The user is required to fill out the input with a value before submitting.用户需要在提交之前用一个值填写输入。 This value must be numerical.该值必须是数字。 Once submitted the parent form and the input are passed to the function:提交父表单后,输入将传递给函数:

...
generateInputs(document.getElementById('input-form'), this)
...

The generate then loops according to the given value inside the input:然后生成根据输入中的给定值循环:

...
x = input.value;
for (y=0; x>y; y++) {
...

Then it generates an input inside the form, on each loop:然后它在表单内生成一个输入,在每个循环中:

...
var element = document.createElement('input');
element.type = "text";
element.placeholder = "New Input";
form.appendChild(element);
...

I have also added in a few CSS stylings to make the inputs look nice, and some placeholders as well.我还添加了一些CSS以使inputs看起来不错,以及一些placeholders To read more about creating elements createElement() :要阅读有关创建元素createElement()更多信息:

https://www.w3schools.com/jsref/met_document_createelement.asp https://www.w3schools.com/jsref/met_document_createelement.asp

To read more about for loops:要阅读有关for循环的更多信息:

https://www.w3schools.com/js/js_loop_for.asp https://www.w3schools.com/js/js_loop_for.asp

        var input = document.createElement("input");

        input.setAttribute("type", "text");

        input.setAttribute("name", "name");

        input.setAttribute("value", 'value');

        document.getElementById("divID").appendChild(input);

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

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