javascript 使用javascript中的按钮单击添加多个文本框

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19130697/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 14:29:35  来源:igfitidea点击:

add multiple textbox using button click in javascript

javascriptphpjqueryhtml

提问by Java Man

Hello I am trying to add multiple textbox when click on button. i have write following HTML code.

您好,我正在尝试在单击按钮时添加多个文本框。我写了以下 HTML 代码。

<script type="text/javascript">
 function addRow(btn) {         
     var parentRow = btn.parentNode.parentNode;
     var table = parentRow.parentNode;
     var rowCount = table.rows.length;
     var row = table.insertRow(rowCount);
     var cell1 = row.insertCell(0);
     var element1 = document.createElement("input");
     element1.type = "text";
     cell1.appendChild(element1);
     var cell3 = row.insertCell(1);
 }
</script>
<table>
   <tr>
      <td><input type="text" name="data1" value="abc" /></td>
      <td><button type="button" onClick ="addRow(this)">Add</button></td>
   </tr>
</table>

i dont know how to do . kindly tell me how to do this stuff .... thank you in advance

我不知道该怎么做。请告诉我如何做这件事......提前谢谢

回答by Tushar Gupta - curioustushar

Wrap your JavaScript code in the head section.

将您的 JavaScript 代码包装在 head 部分中。

DEMO of your code

您的代码的演示

same code with jQuery

与 jQuery 相同的代码

DEMO

演示

var txtbox = '<td><input type="text"/></td>';

function addRow(btn) {
    $(btn).closest('tr').append(txtbox);
}

DEMO

演示

var txtbox = '<tr><td><input type="text"/></td></td>';

function addRow(btn) {
    $(btn).closest('table').append(txtbox);
}

References

参考

.closest()

.closest()

.append()

。附加()

To add Drop-down list

添加下拉列表

you just need to add dropdown list code in the var txtbox

你只需要在下拉列表中添加代码 var txtbox

DEMO

演示

var txtbox = '<tr><td><select><option value="volvo">Volvo</option><option value="saab">Saab</option><option value="mercedes">Mercedes</option><option value="audi">Audi</option></select></td></td>';

function addRow(btn) {
    $(btn).closest('table').append(txtbox);
}

回答by Sindhu

try this sample...

试试这个样本...

var emails = document.getElementById('emails'),
 add_link = document.createElement('a'),
 template = emails.getElementsByTagName('div'),
 current = template.length,
 max = 20;
 template = template[0];

 submit1.onclick = function () {
 var new_field = template.cloneNode(true);
 current += 1;
 new_field.innerHTML = new_field.innerHTML.replace(/1/g, current);
 emails.appendChild(new_field);
if (current === max) {
    add_link.onclick = null;
    document.body.removeChild(add_link);
}
return false;
};

document.body.appendChild(add_link);

For demo http://jsfiddle.net/wQfLT/145/

对于演示http://jsfiddle.net/wQfLT/145/