简体   繁体   中英

JavaScript change input type=“text” to type=“file”

So I have a code that is like this:

<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()" />

It is supposed to change the text field to a file upload field and vise versa.

The current code isn't working. Any ideas of what I should do to fix this?

The problem is with the cloning. You cannot change the type of an existing element, you can only set the type for a new element (once).

Try this

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';
    }
}

Working example on jsbin

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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