gpt4 book ai didi

javascript - 原型(prototype) : add/remove input element

转载 作者:太空宇宙 更新时间:2023-11-04 15:41:10 26 4
gpt4 key购买 nike

我正在创建文件(图片)上传表单。我想通过单击按钮添加输入元素。

这是我的输入:

<input type="file" name="file"/>

我已经写了一些代码:

        <script language="javascript">
fields = 0;
function addInput() {
if (fields < 10) {
document.getElementById('text').innerHTML += "<input type="file" name="file"/><br />";
fields += 1;
} else {
document.getElementById('text').innerHTML += "<br />Only 10 upload fields allowed.";
document.form.add.disabled=true;
}
}
</script>

但是它很丑而且行不通......

我有原型(prototype)库,想用它来添加输入。

所以我需要一个按钮来添加给定的输入和每个输入附近的更多按钮以将其删除 - 就像您将文件附加到邮件时一样。

最佳答案

[ See it in action ]

HTML

<div id="text"></div>
<div id="warning"></div>

Javascript

fields = 0;

function addInput() {
if (fields < 10) {
var id = "file" + fields;
document.getElementById('text').innerHTML +=
"<div><input type='file' name='"+id+"' />" +
" <a href='#' onclick='removeInput(this.parentNode)' />remove</div>";
fields += 1;
} else {
document.getElementById('warning').innerHTML =
"Only 10 upload fields allowed.";
document.form.add.disabled = true;
}
}

function removeInput( el ) {
if (fields > 0) {
document.getElementById('warning').innerHTML = "";
var parent = document.getElementById('text');
parent.removeChild(el);
fields -= 1;
}
}

关于javascript - 原型(prototype) : add/remove input element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3186209/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com