PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, November 19, 2022

[FIXED] How to write custom-file-input text with css

 November 19, 2022     bootstrap-4, css, html, javascript, jquery     No comments   

Issue

I'm using Bootstrap4 to design my html page and I'm implementing a custom-file-input bar.

I want to get the three labels of the input bar ("Choose file", "Browse", "Upload") from my css file, so I've defined three custom classes and their content in the css file. Here is the code:

.CHOOSE_FILE_LABEL::before{content: 'Choose file';}
.BROWSE_BTN_LABEL::after{content: 'Browse';}
.UPLOAD_BTN_LABEL::after{content: 'Upload';}
<div class="input-group">
  <div class="custom-file">
    <input type="file" class="custom-file-input" id="customFileInput">
    <label class="custom-file-label CHOOSE_FILE_LABEL BROWSE_BTN_LABEL" for="customFileInput"></label>
  </div>
  <div class="input-group-append">
    <button class="btn btn-success UPLOAD_BTN_LABEL" type="button" id="uploadBtn"></button>
  </div>
</div>

Then I want to replace the label of the input bar ("Choose file") with the name of the file when a file is selected. So I use the following JS code:

// replace "Choose file" with the file name
document.getElementById("customFileInput").addEventListener('change', function (e)  
{
  e.preventDefault();
  var file_input =  document.getElementById("customFileInput");
  var file_name = file_input.files[0].name;
  var next_sibling = e.target.nextElementSibling;
  next_sibling.innerText = file_name;
});

The problem is that the name of the selected file is concatenated with (and not replaced by) "Choose file". Can I do that with JS or should I change my css file?

Here is the full code: https://jsfiddle.net/5csLd90b/2/


Solution

If you can change your file input to be required then you can use CSS :valid and next selector to target the label, eg:

<input type="file" class="custom-file-input" id="customFileInput" required>
.custom-file-input:valid + .CHOOSE_FILE_LABEL::before{content: '';}

Updated fiddle: https://jsfiddle.net/50wqt4gx/

Otherwise you can add a class using js to your file input (or label) and apply ::before based on that class, eg:

file_input.classList.add("hasfile")
.custom-file-input.hasfile + .CHOOSE_FILE_LABEL::before{content: '';}


Answered By - freedomn-m
Answer Checked By - Pedro (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing