0

If user is selecting file and after it if user is unchecking checkbox than file is also at there so I want to make it like a when user is unchecking checkbox than after file is must be remove. How can I make it? And which event handler is perfect for checkbox? HTML CODE:

<div class="checkbox">
  <label for="email">electronics
  <input type="checkbox" name="product_category[]" value="electronics" id="product_category" class="electronics">
  </label>
</div>
<div class="form-group" id="efileu" style="display:none;" >
  <input type="file" name="checkboxfile0" id="efile"   style="width:100%">
</div>
<div class="checkbox">
  <label for="email">kitchen
  <input type="checkbox" name="product_category[]" value="kitchen" id="product_category" class="kitchen">
</div>
<div class="form-group" id="kfileu" style="display:none;" >
  <input type="file" name="checkboxfile1" id="kfile"   style="width:100%">
</div>

<script>
$(".electronics").click(function(){
    if(!$("#efileu").is(":visible")){
      $("#efileu").show();
    }
    else{
      $("#efileu").hide();
      $("#efileu").val();
    }

});
$(".kitchen").click(function(){
    if(!$("#kfileu").is(":visible")){
      $("#kfileu").show();
    }
    else{
      $("#kfileu").hide();
    }

});
</script>
shah rushabh
  • 19
  • 2
  • 9
  • Missing `` for kitchen – Rani Kheir Sep 25 '16 at 02:05
  • 1
    If you want to remove the value of the `input.file` object, you should clear it's value with `$("#efileu input").val("");`. See https://jsfiddle.net/shaoran/rathxw43/ – Pablo Sep 25 '16 at 02:36
  • It may seem that just using `.val("")` is not enough, see http://stackoverflow.com/questions/1043957/clearing-input-type-file-using-jquery – Pablo Sep 25 '16 at 02:43

2 Answers2

5

use this one line of jQuery in your existing code that seems fine to me

else{
    $("#efileu").hide();
    $("#efileu").replaceWith($("#efileu").val('').clone(true)); //clear the values
}

else{
    $("#kfileu").hide();
    $("#kfileu").replaceWith($("#kfileu").val('').clone(true));//clear the values
}
esote
  • 763
  • 10
  • 24
Asifuzzaman Redoy
  • 1,677
  • 1
  • 10
  • 26
1

Found a workaround that works:

  $(".electronics").click(function() {
    if (!$("#efileu").is(":visible")) {
      $("#efileu").show();
    } else {
      var $el = $('#efileu');
      $el.wrap('<form>').closest('form').get(0).reset();
      $el.unwrap();
      $("#efileu").hide();
    }

Here's a JSFiddle to see it in action. Credit goes to Gyrocode.

Community
  • 1
  • 1
Rani Kheir
  • 929
  • 11
  • 14