shah rushabh
shah rushabh

Reputation: 39

how to remove form input data on clicking on checkbox?

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>

Upvotes: 0

Views: 144

Answers (2)

Asifuzzaman
Asifuzzaman

Reputation: 1783

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
}

Upvotes: 5

Rani Kheir
Rani Kheir

Reputation: 1079

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.

Upvotes: 1

Related Questions