• jQuery Video Tutorials

jQuery :file Selector



The :file selector in jQuery is used to select all <input> elements of type file.

The <input type ="file"> element is used in HTML forms to create a control (usually a button labeled "Choose file") allows users to select and upload files from their device to a web server.

Syntax

Following is the syntax of :file selector in jQuery −

$(":file")

Parameters

Following are the parameters of this method −

  • ":file" − This selector selects all <input> elements of type file.

Example 1

In the following example, we are using the :file selector to apply a blue border to all file input elements −

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $("input:file").css("border", "2px solid blue");
        });
    </script>
</head>
<body>
    <form>
        <label for="file1">Choose file:</label>
        <input type="file" id="file1" name="file1"><br><br>
        <label for="file2">Choose another file:</label>
        <input type="file" id="file2" name="file2"><br><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

After executing the above program, the <input> elements of type "file" will be selected and highlighted with blue colored border around them.

Example 2

This example uses the :file selector to set up an event handler that alerts the file path of the selected file when the user chooses a file −

<html>
<head>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        $(document).ready(function() {
            $("input:file").on("change", function() {
                alert("File selected: " + $(this).val());
            });
        });
    </script>
</head>
<body>
    <form>
        <label for="file3">Select a file:</label>
        <input type="file" id="file3" name="file3"><br><br>
        <label for="file4">Select another file:</label>
        <input type="file" id="file4" name="file4"><br><br>
        <input type="submit" value="Submit">
    </form>
</body>
</html>

After executing, click the "Choose file" button and upload any file. Then an alert will be popped displaying the file path of the uploaded file.

jquery_ref_selectors.htm
Advertisements