CSS selector for empty file input

I know that inputting a style file is pretty minimal, which is not so bad.

Is there a way to select the input of a file that is empty?

The plan is to show or hide the submit button, depending on whether the file is empty.

+5
source share
2 answers

If you prefer labeling input as required , you can only do this with css :

 input:invalid ~ .chosen { display: none; } input:valid ~ .empty { display: none; } 
 <input type="file" required><br> <span class="empty">Empty</span> <span class="chosen">Chosen</span> 
+8
source

Is there a way to select the input of a file that is empty?

No.

You will need JavaScript. Here you can find some answers on SO and in other places. The main idea is to observe the change event element, add a class, such as non-empty , indicating that there are files, and then the input[type="file"].non-empty + label style input[type="file"].non-empty + label , provided that you use the technique of using label as the file to replace the enter button. You will need a special case of form.reset() , which entangles input files in the form, but does not raise a change event in the input. Here is a sample code (without the form.reset part):

 // Add a class to a file input if it not empty. function mark() { this.classList.toggle('non-empty', this.files.length); } // Watch a file input and update non-empty status. function watch(input) { input.addEventListener('change', mark); } // Get all file inputs. const inputs = Array.from(document.querySelectorAll('input[type=file]')); // Watch all file inputs in the whole document. inputs . forEach(watch); 
 input[type="file"] { width: 0.1px; height: 0.1px; } input[type="file"].non-empty + label { color: green; } input[type="file"].non-empty + label::after { content: ' (specified)'; } 
 <input type="file" id="input"> <label for="input">Specify file</label> 
+3
source

Source: https://habr.com/ru/post/1271379/


All Articles