Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to only clear file upload field?

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

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

My 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:

$('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 + '\')" />');
});
like image 497
Rails beginner Avatar asked Feb 02 '12 19:02

Rails beginner


People also ask

How do I empty input field files?

To reset a file input in React, set the input's value to null in your handleChange function, e.g. event. target. value = null . Setting the element's value property to null resets the file input.

How do you clear the input in HTML?

Resetting a file input is possible and pretty easy with jQuery and HTML. For that purpose, you should wrap a <form> around <input type="file">, then call reset on the form by using the reset() method, then remove the form from the DOM by using the unwrap() method.

What is the value of input type file?

A file input's value attribute contains a string that represents the path to the selected file(s). If no file is selected yet, the value is an empty string ( "" ). When the user selected multiple files, the value represents the first file in the list of files they selected.


3 Answers

How about:

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

Example: jsFiddle

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

like image 158
j08691 Avatar answered Oct 27 '22 01:10

j08691


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>
like image 26
Friend Avatar answered Oct 27 '22 01:10

Friend


You can do simply

  $("#filuploadId")[0].value = "";
like image 41
Shahbaz Ahmad Avatar answered Oct 27 '22 00:10

Shahbaz Ahmad