如何只清除文件上传字段

How to only clear file upload field?

本文关键字:字段 文件 清除      更新时间:2023-09-26

这是JSfiddle:http://jsfiddle.net/buyC9/128/

当按下清除时,我只想清除文件上传字段。

我的HTML:

<h1>Upload image:</h1>
<input type="file" name="blog[opload]" id="blog_opload" class="imagec">
<input type="url" size="50" name="blog[url]" id="blog_url" class="imagec">
<div id="preview">
</div>

我的Jquery:

$('input').change(function() {
    var el = $(this);
    if (this.value === "") {
        $('.imagec').prop('disabled', false);
        this.disabled = false;
        $('#preview').hide();
    } else {
        $('.imagec').prop('disabled', true);
        el.prop('disabled', false);
        alert(el.val());
        if (el.attr('type') == 'url') {
            $('#preview').show().html('<img src=' + '"' + el.val() + '"' + ' />');
        }
    }
});
function reset_html(id) {
    $('.' + id).html( $('.' + id).html() );
}
var imagec_index = 0;
    $('input[type=file]').each(function() {
    imagec_index++;
    $(this).wrap('<div id="imagec_' + imagec_index + '"></div>');
    $(this).after('<input type="button" value="Clear" onclick="reset_html(''imagec_' + imagec_index + ''')" />');
});

怎么样:

$('input[value="Clear"]').click(function(){
    $('#blog_opload').val('');
});

示例:jsFiddle

如果你使用这个,你也可以去掉onclick="reset_html(''imagec_' + imagec_index + ''')"

快速答案是替换它:

$("#clear").click(function(event){
  event.preventDefault();
  $("#control").replaceWith("<input type='file' id='control' />");
});
<input type="file" id="control" />
<a href="#" id="clear">Clear</a>

您可以简单地进行

  $("#filuploadId")[0].value = "";

在您的代码中,您本想使用ID选择器,但却使用了类选择器。

$('.' + id).html( $('.' + id).html() );

应该是

$('#' + id).html( $('#' + id).html() );

更新的jsFiddle