Kyle Underhill
Kyle Underhill

Reputation: 109

jQuery - Reset file input and update button on click

Only when a file is uploaded and .submit is clicked will the button change its HTML from 'Submit' to 'Sent'. I want to reset the button back to its original state after it has been cleared by clicking the .reset button.

The problem is I don't know how to clear the file and have the button reset it's html back to 'submit'.

$(document).on("click", ".submit", function(e) {
  var $uploader = $(this).closest(".item").find("input");
  if ($uploader.val() !== "") {
    e.preventDefault();
    $(this).html("Sent");
  } else {
    console.log("Please upload a file");
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="item">
  <div class="elements">
    <input type="file">
    <button class="reset">reset</button>
  </div>
  <button class="submit">Submit</button>
</div>

Upvotes: 0

Views: 135

Answers (1)

ikiK
ikiK

Reputation: 6532

Just set value back to empty, like on any input filed you want to clear:

$uploader.val("")

And set the button back to same way you set it to sent

.html("Submit")

Also added code for reset button.

$(document).on("click", ".submit", function(e) {
  var $uploader = $(this).closest(".item").find("input");
  if ($uploader.val() !== "") {
    e.preventDefault();
    $(this).html("Sent");
    $uploader.val("")
  } else {
    console.log("Please upload a file");
  }
});

$(document).on("click", ".reset", function(e) {
  var $uploader = $(this).closest(".item").find("input");
  var $submit = $(this).closest(".item").find(".submit");
    $submit.html("Submit");
    $uploader.val("")
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="item">
  <div class="elements">
    <input type="file">
    <button class="reset">reset</button>
  </div>
  <button class="submit">Submit</button>
</div>

Upvotes: 1

Related Questions