×

jQuery Tutorial

jQuery Examples

jQuery Practice

Clearing <input type='file' /> using jQuery

Learn, how to clear the selected file in an input and also how can be clear the complete form and reset it back to the default using jQuery?
Submitted by Pratishtha Saxena, on December 23, 2022

When the input field is of type = 'file' then it allows you to select any document file (.pdf, .doc, .jpg, .png, etc.). Therefore, there should be a way to clear the selected file just in case the user selects the wrong file. For this, we can set the input 'value' attribute as none, i.e., val(' '). Hence, this will allow the input field to reset back to the initial.

Syntax:

 $('selector').val('');

We can also use the jQuery reset() method for the same. Let's use this method for resetting the complete form back to default.

jQuery reset() Method

This is a jQuery built-in method, which helps clear up all the input values within a form in one go.

Syntax:

$(selector)[0].reset();

The form is selected using the appropriate selector and then it is reset using the reset() method. This reset method can be set as a function for a click event of a button.

Let's understand this better with the help of an example:

jQuery example to clear <input type='file' />

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <title>Document</title>
    <style>
      button{
      margin-left: 10px;
      margin-right: 10px;
      }
    </style>
  </head>
  
  <body>
    <h2>Clearing  input type='file'  using jQuery</h2>
    <h4>Click the button to clear the selected file.</h4>
    <button id="one">Reset File</button>
    <button id="two">Reset Form</button>
    <hr>
    <br>
    <b>
      <form>
        Name: <input type="text" value=""><br><br>
        Email Id: <input type="email" value=""><br><br>
        Contact: <input type="number" value=""><br><br>
        Resume: <input type="file" value="" id="file"><br><br><br>
        <button>Submit</button>
      </form>
      <hr>
    </b>
    <h4 id="one"></h4>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $('button#one').click(function(){
            $('input#file').val('');
            $('h4#one').html('File has been reset');
        });
    
        $('button#two').click(function(){
            $('form')[0].reset();
            $('h4#one').html('Form has been reset');
        });
    });  
  </script>
</html>

Output:

Example 1: Clearing <input type='file' /> using jQuery
Example 2: Clearing <input type='file' /> using jQuery




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.