javascript 如何只清除文件上传字段?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9118738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 05:39:29  来源:igfitidea点击:

How to only clear file upload field?

javascriptjquery

提问by Rails beginner

Here is the JSfiddle: http://jsfiddle.net/buyC9/128/

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

I want to clear only the file upload field when pressed on clear.

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

My HTML:

我的 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>

My Jquery:

我的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 + '\')" />');
});

回答by j08691

How about:

怎么样:

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

Example: jsFiddle

示例:jsFiddle

You could also get rid of onclick="reset_html(\'imagec_' + imagec_index + '\')"if you use this.

onclick="reset_html(\'imagec_' + imagec_index + '\')"如果你使用它,你也可以摆脱。

回答by Developer

Quick answer is replace it:

快速回答是更换它:

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

<input type="file" id="control" />
<a href="#" id="clear">Clear</a>

回答by Shahbaz Ahmad

You can do simply

你可以简单地做

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

回答by amit_g

In your code you meant to use the ID selector but instead are using class selector.

在您的代码中,您打算使用 ID 选择器,而是使用类选择器。

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

should be

应该

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

Updated jsFiddle

更新了 jsFiddle