2012-02-02 66 views
3

這裏是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 + '\')" />'); 
}); 
+0

你爲什麼不使用插件是什麼? – gdoron 2012-02-02 19:36:40

+3

我爲什麼要? – 2012-02-02 19:37:20

+1

你是什麼意思「按清除」? – j08691 2012-02-02 19:38:34

回答

6

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> 
0

在你的代碼,你想用的ID選擇,而是使用類選擇。

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

應該

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

Updated jsFiddle

6

如何:

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

例子:jsFiddle

如果你使用這個,你也可以擺脫onclick="reset_html(\'imagec_' + imagec_index + '\')"

1

你可以做簡單的

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