用另一个动态创建的输入替换输入

时间:2013-09-04 14:49:20

标签: javascript jquery html internet-explorer

我想完全用文本输入字段替换现有的文件输入字段,所有属性都保持不变,如idname等。如何使用jQuery进行此操作?

前奏

我有一个<input type="file" name=".." id=".." />我用于基于AJAX的上传。 (是的,对于IE,我使用IFRAME s提交表单。)

上传完成后,我会进入我的成功回调函数,我尝试将原始<input type="file"更改为<input type="text"

在其他浏览器中,只需运行以下代码就可以正常工作:

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

但这不适用于IE,我从SO中了解到这是一个安全问题,因此不允许。我想为此编写最小代码。

5 个答案:

答案 0 :(得分:1)

从user2259571的回答中,我以较短的单行方式完成了以下操作:

$originalInput
    .replaceWith( $originalInput[0].outerHTML.replace(/type="file"/, 'type="input"') );

答案 1 :(得分:0)

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 :(得分:0)

IE不允许这样做,但解决方法可以是:

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

jQuery change input type

可能重复

答案 3 :(得分:0)

我认为你可以通过放置两个输入来实现这一点,

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

在您请求回拨中,您可以删除type="file"输入字段,删除“-after” 后缀并显示type="text"输入字段。

答案 4 :(得分: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/

相关问题