GROVER.
GROVER.

Reputation: 4388

When File Selected Change Label Contents jQuery

So, I'm attempting to make my file upload input look a little bit better than the default buttons. All is going well, however, I can't seem to find a jQuery script which can do what I want it to do.

What I want to happen is, when a file isn't selected, I would like the label to display "Choose an avatar", but when a file is selected, I would like it to display the files name, i.e: "example.png" instead of "Choose an avatar".

This is my HTML:

<form action="" method="post" class="avatar-form-form" enctype="multipart/form-data">
    <input id="avatar-file" type="file" name="avatar">
    <label for="avatar-file">Choose An Avatar</label>
</form>

Also, if the user selects multiple files, I would like it to say "Too many files selected."

All help is appreciated as I am new to jQuery.

Upvotes: 2

Views: 2029

Answers (1)

Nenad Vracar
Nenad Vracar

Reputation: 122087

You can set text() of label as val of input, and for multiple files you would have to use multiple

$('input').change(function() {
  $(this).next('label').text($(this).val());
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" class="avatar-form-form" enctype="multipart/form-data">
  <input id="avatar-file" type="file" name="avatar">
  <label for="avatar-file">Choose An Avatar</label>
</form>

If you want to hide default file input's text you can use color: transparent in CSS DEMO

Upvotes: 4

Related Questions