Reputation: 78
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?
Upvotes: 1
Views: 1214
Reputation: 16544
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
Upvotes: 3