JavaScript更改输入类型="文本"输入="文件"

时间:2014-05-06 09:09:54

标签: javascript

所以我有一个像这样的代码:

<script type="text/javascript">
function fundx() {
    var input = document.getElementById("id");
    var input2 = input.cloneNode(false);
    if (document.getElementById("butid").value == 'Upload') {
        input2.type = 'text';
        input.parentNode.replaceChild(input2, input);
        document.getElementById("butid").value = 'URL';
    } else {
        input2.type = 'file';
        input.parentNode.replaceChild(input2, input);
        document.getElementById("butid").value = 'Upload';
    }
}
</script>
<input id="id" type="text" name="id"  value="Upload" />
<input type="button" id="butid" value="Upload" onclick="fundx()" />

应该将文本字段更改为文件上载字段,反之亦然。

目前的代码不起作用。我应该怎么做才能解决这个问题?

1 个答案:

答案 0 :(得分:3)

问题在于克隆。您无法更改现有元素的类型,只能为新元素设置类型(一次)。

试试这个

function fundx() {
    var input = document.getElementById("id");
    var input2 = document.createElement('input');
    input2.id = input.id;
    input2.name = input.name;
    input2.value = input.value;
    if (document.getElementById("butid").value == 'Upload') {
        input2.type = 'text';
        input.parentNode.replaceChild(input2, input);
        document.getElementById("butid").value = 'URL';
    } else {
        input2.type = 'file';
        input.parentNode.replaceChild(input2, input);
        document.getElementById("butid").value = 'Upload';
    }
}

jsbin

上的工作示例