renat natanael renat natanael - 5 months ago 15
Javascript Question

show button reset when input file have value

i try to create a button reset for input file. everytime input file have value then a button show up to reset the input file. the problem is, i have 6 input file. and when i upload an image on one of the input file, all button show up, even the other input file didnt have value yet.
how to make specific for the button?

my code like this

$("#inputFile1").change(function(){
if($(this).val() == "")
$('.reset').css({"display": "none"});
else
$('.reset').css({"display": "block"});
})
$("#inputFile2").change(function(){
if($(this).val() == "")
$('.reset').css({"display": "none"});
else
$('.reset').css({"display": "block"});
})
$("#inputFile3").change(function(){
if($(this).val() == "")
$('.reset').css({"display": "none"});
else
$('.reset').css({"display": "block"});
})


heres jsfiddle
https://jsfiddle.net/30uv0kfa/

Answer

I surrounded each group of input file and button with a div and simplified your JS code.

$(document).ready(function() {
  $(".input-file").on("change", function(){
    if($(this).val() == "") {
      $(this).parent().find(".reset").css({"display": "none"});
    } else {
      $(this).parent().find(".reset").css({"display": "block"});
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input class="input-file" id="inputFile1" type="file"/>
  <button class="reset" style="display:none">reset</button>
</div>
<div>
  <input class="input-file" id="inputFile2" type="file"/>
  <button class="reset" style="display:none">reset</button>
</div>
<div>
  <input class="input-file" id="inputFile3" type="file"/>
  <button class="reset" style="display:none">reset</button>
</div>
<div>
  <input class="input-file" id="inputFile4" type="file"/>
  <button class="reset" style="display:none">reset</button>
</div>
<div>
  <input class="input-file" id="inputFile5" type="file"/>
  <button class="reset" style="display:none">reset</button>
</div>

Comments