1

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?

4
  • Works fine for me, what browser are you testing this in? Commented May 6, 2014 at 9:12
  • where do the extra characters "; at the end of line 16 come from? Commented May 6, 2014 at 9:15
  • not a best solution, but works. what errors do you have in cosole? Commented May 6, 2014 at 9:17
  • @devnull69: Sorry, it was part of the code of the php section, I'll remove them. @ putvande , deadulya : I've tried it in w3 schools "try it editor". It doesn't work. Commented May 6, 2014 at 9:18

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.