简体   繁体   English

选择文件时更改标签内容 jQuery

[英]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.一切都很顺利,但是,我似乎无法找到一个可以完成我想要它做的事情的 jQuery 脚本。

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, ie: "example.png" instead of "Choose an avatar". 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, ie: "example. png”而不是“选择头像”。

This is my HTML:这是我的 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.感谢所有帮助,因为我是 jQuery 的新手。

You can set text() of label as val of input, and for multiple files you would have to use multiple您可以设置text()标签作为val输入,并为多个文件,你将不得不使用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如果你想隐藏默认file输入的文本,你可以在 CSS DEMO 中使用color: transparent

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM