1

I want to replace an existing file input field entirely with a text input field, with all properties intact like id, name, etc. How do I do that using jQuery?

Prelude:

I have an <input type="file" name=".." id=".." /> that I am using for AJAX based uploads. (yes, For IE, I am submitting the form using IFRAMEs.)

When the upload is done, I go into my success callback function, where I am trying to change the original <input type="file" to <input type="text".

In other browsers, this is working fine when I simply run the following code:

$originalInput[0].type = 'text';
$originalInput[0].value = 'response code';

But this is not working in IE, where I came to know from SO that it is a security concern and hence not allowed. I want to write minimum code for this.

2
  • 1
    how about removing the old input and inserting a new one? Commented Sep 4, 2013 at 14:52
  • How to do that with minimum code? Do I need to create an input in jQuery dynamically and iterate all properties of original input pushing them to new? Commented Sep 4, 2013 at 14:53

5 Answers 5

1

From user2259571's answer, I did this following in a shorter one-line way:

$originalInput
    .replaceWith( $originalInput[0].outerHTML.replace(/type="file"/, 'type="input"') );
Sign up to request clarification or add additional context in comments.

Comments

0

IE does not allow this, but a workaround can be:

$('body').find('input:file').each(function() {
  $("<input type='text' />").attr({value: 'response code' }).insertBefore(this);
}).remove();

possible duplicate of jQuery change input type

Comments

0

I think you can reach this very simple by placing two inputs,

<input type="file" name="somename1" id="someid1"/>
<input type="text" name="somename1-after" id="someid1-after" style="display:none"/>

In you request callback you can remove the type="file" input field, strip the "-after" suffix and show the type="text" input field.

Comments

0

Long live jQuery

    var fileInput = $('input[type="file"]');
    var textInput = $('<input type="text"/>');

    //can copy properties here 
    textInput.value = 'response code';
    textInput.className = fileInput.className;

textInput.insertBefore(fileInput);
textInput.remove();

2 Comments

How do I copy all the properties of previous file input into new text input?
you can use attr method or just by simple JavaScript
0
var input = $("input[type=file]");
var inputHTML = input.clone().wrapAll("<div>").parent().html();

var newinputHTML = inputHTML.replace(/type="file"/, 'type="text"');

input.replaceWith(newinputHTML);

http://jsfiddle.net/QdZDb/1/

2 Comments

This is cool. I changed it to: input.replaceWith(input[0].outerHTML.replace(/type="file"/, 'type="input"'));
outerHTML might not work on Firefox quirksmode.org/dom/w3c_html.html

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.