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.

KingJulian
  • 893
  • 8
  • 16

5 Answers5

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"') );
KingJulian
  • 893
  • 8
  • 16
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();
Moazzam Khan
  • 2,888
  • 2
  • 17
  • 32
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

Community
  • 1
  • 1
lomas09
  • 1,104
  • 4
  • 12
  • 27
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.

Martin
  • 2,076
  • 1
  • 19
  • 39
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/

KingJulian
  • 893
  • 8
  • 16
Emery Lapinski
  • 1,342
  • 17
  • 22