Reputation: 217
It works fine when I select / deselect a file via the Choose File button:
$("input[type='submit']").toggle(false);
$("input[type='file']").change(function() {
if ($(this).val() != "") {
$("#btn").toggle();
} else {
$("#btn").toggle();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="fld" type="file" name="image" id="file">
<input id="btn" type="submit" value="Upload / Edit picture" name="upload_picture" id="upload_picture" class="btn" />
<br>
<br>
<div id="remove_button">Remove</div>
Click on the Choose File button and select a file. The Upload / Edit picture button will appear. Now click on the Choose File button again but do not select a file and exit the small popup window. The Upload / Edit picture button will disappear.
In my case I want the input="file" value to be cleared and the Upload / Edit picture button to disappear if I clear the value by clicking on the <div id="remove_button">Remove</div>
Is there a way to do that?
Upvotes: 1
Views: 745
Reputation: 753
Add this code into your javascript
$("#btn").toggle(false);
$("#fld").change(function(){
if($(this).val() != "")
{
$("#btn").toggle();
}
else{
$("#btn").toggle();
}
});
$("#remove_button").click(function(){
$("#fld").val('');
document.getElementById("btn").style.visibility = "hidden";
})
and remove id tag from your html..it has two ids for the button change it like
<input id="btn" type="submit" value="Upload / Edit picture" name="upload_picture"
class="btn" />
Upvotes: 1
Reputation: 66153
What you can do is to bind a click event listener to the #remove_button
element (which I recommend that you should be using <button>
instead of a <div>
).
In the callback, you can simply set the value of the file input to an empty string, which effectively resets the field. Remember that you will need to use .trigger('change')
to manually reinvoke the show/hide logic based on the file input value:
const $submit = $("input[type='submit']");
$submit.hide();
$("#fld").change(function() {
$submit.toggle(!!this.value);
});
$('#remove_button').click(function() {
$('#fld').val('').trigger('change');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="fld" type="file" name="image" id="file">
<input id="btn" type="submit" value="Upload / Edit picture" name="upload_picture" id="upload_picture" class="btn" />
<br>
<br>
<button id="remove_button">Remove</button>
Upvotes: 1