Please label the attached file

Looking for assistance with adding a label next to the "Attachment" button that displays the file name selected by the user in a contact form. The code provided utilizes CSS, HTML, and JavaScript to achieve this functionality. Any input or suggestions would be greatly appreciated. Thanks!

 // JavaScript function to handle opening the navigation menu
      function openNav() {
          document.getElementById("myNav").classList.remove("collapsed");
          var input = document.getElementById("txtDetail");
          var value = input.value;
          var label = document.getElementById("labelDetail");
          label.innerHTML = value;

          // Additional functions to update labels based on user input

          document.getElementById("myNav").style.width = "100%";
      }

      // Function to close the navigation menu
      function closeNav() {
          document.getElementById("myNav").style.width = "0%";
          document.getElementById("myNav").classList.add("collapsed");
      }
 /* CSS Styles for the contact form */
      ... 
      
 /* HTML Structure of the Contact Form */
      ...
    

Answer №1

Create an element, such as a <span>, to come after the <label> that references the <input type="file"> element with the use of the for attribute. Upon the change event of the <input type="file">, extract the name from .files[0] and set this value to the .innerHTML property of the span.

Note that the styling for the span has been left out of this answer.

function openNav() {
        document.getElementById("myNav").classList.remove("collapsed");
        var input = document.getElementById("txtDetail");
        var value = input.value;
        var label = document.getElementById("labelDetail");
        label.innerHTML = value;

        var input = document.getElementById("txtName");
        var value = input.value;
        var label = document.getElementById("labelName");
        label.innerHTML = value;

        var input = document.getElementById("txtNumber");
        var value = input.value;
        var label = document.getElementById("labelNumber");
        label.innerHTML = value;

        var input = document.getElementById("txtEmail");
        var value = input.value;
        var label = document.getElementById("labelEmail");
        label.innerHTML = value;

        document.getElementById("myNav").style.width = "100%";
    }

    function closeNav() {
        document.getElementById("myNav").style.width = "0%";
        document.getElementById("myNav").classList.add("collapsed");
    }
    
    document.getElementById("file-upload")
    .addEventListener("change", function() {
      this.labels[0].nextElementSibling.innerHTML = this.files[0].name;
    })
* {
      margin: 0;
      padding: 0;
      box-sizing: border-box;
      -webkit-box-sizing: border-box;
      -moz-box-sizing: border-box;
      -webkit-font-smoothing: antialiased;
      -moz-font-smoothing: antialiased;
      -o-font-smoothing: antialiased;
      font-smoothing: antialiased;
      text-rendering: optimizeLegibility;
    }

    ... (CSS Styles omitted for brevity)
   
</fieldset>
              <fieldset class="fieldset">
                <label id="labelAttach">Attachment:</label>
                <label id="labelFile">File</label>
                <button name="submit" id="contact-submit" data-submit="...Sending">Submit</button>
              </fieldset>
            </div>
          </div>  
        </div>  
        <span id="button" onclick="openNav()">Preview</span>
      </fieldset>
    </form>
  </div>

Answer №2

Hey there! This code snippet is set up to work just the way you need it to. Take a look:

I've included some JS that you can easily copy and paste into your project, allowing it to handle the task at hand!

Within this piece of code, I'm extracting the value from the input element, which represents a path. By utilizing the substring method, we're able to isolate and retrieve the desired content - in this case, the file name.

document.getElementById('file-upload').onchange = showText;
function showText() {
  var fileVal = this.value;
  var last = fileVal.lastIndexOf("\\");
  if (last >= 0) {
    fileVal = fileVal.substring(last + 1);
  }
  document.getElementById('fileValue').innerText = fileVal;
}
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  -webkit-font-smoothing: antialiased;
  -moz-font-smoothing: antialiased;
  -o-font-smoothing: antialiased;
  font-smoothing: antialiased;
  text-rendering: optimizeLegibility;
}

input[type="file"] {
  display: none;
}

.custom-file-upload {
  cursor: pointer;
  padding: 13px 16px;
  width: 125px;
  height: 45px;
  border: none;
  font-family: Verdana;
  background: #4CAF50;
  color: #FFF;
  margin: 0 0 5px;
  font-size: 15px;
  display: inline-block;
  vertical-align: top;
  text-align: center;
}

.custom-file-upload:hover {
  background: #43A047;
  -webkit-transition: background 0.3s ease-in-out;
  -moz-transition: background 0.3s ease-in-out;
  transition: background-color 0.3s ease-in-out;
}

.custom-file-upload:active {
  box-shadow: inset 0 1px 3px rgba(0, 0, 0, 0.5);
}
<label for="file-upload" class="custom-file-upload">
<i class="fa fa-cloud-upload"></i> Attachment
</label>
<input id="file-upload" type="file" />
<p id="fileValue" style="display: inline-block"></p>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for repairing buttons in the CSS container

The buttons in the CSS search-box are not staying fixed as intended. They should be within the search box, but instead, they are protruding out of the panel. I attempted to utilize z-index, but it did not produce the desired outcome. https://i.sstatic.n ...

Generate a fresh object with distinct identifiers

I am interested in creating a new object, utilizing unique keys consisting of comma-separated IDs. For instance, I have: const d = { "1,2,3,4,5,6,7,8,9,10": [ "created_by", "modified_on", "external_o ...

Can we disable hydration warnings for all nested children within a component in NextJS?

Note: I am currently using NextJS 14, but I suspect this issue also exists in NextJS 13. I have created a ThemeToggle component that utilizes the next-themes package. Even if I develop my own version of next-themes using React Context or another state man ...

Is it possible to remotely adjust JavaScript configurations on the client's side using JSON?

I have integrated my library into the client's website and need to set it up by providing a remote JSON file specific to the client's ID. What would be the most effective method for achieving this? Using ajax directly may not be ideal as we need ...

Converting JavaScript to JSON and saving dynamic properties

Having a basic knowledge in JavaScript, I am attempting to extract data from users and utilize it as JSON properties in the following format: <th colspan="2"><input id="dc_name" name='dc[name]'></input></th> $ ...

Utilizing NodeSize to Optimize the Spacing Among Nodes in the D3 Tree Arr

Currently, I am trying to adjust the positioning of my rectangle nodes because they are overlapping, as illustrated in the image below: In my research, I discovered that D3 provides a nodeSize and separation method. However, I encountered difficulties imp ...

Incorporating the Acts_as_votable gem alongside Angularjs for interactive voting functionality

I'm trying to figure out how to implement Acts_as_Votable in an Angular template for a car voting system. Despite my efforts, I can't seem to display the vote count when rendering the list in Angular. I think I may need to establish some kind of ...

The 404 error message was encountered when attempting to fetch the Ajax

I am experimenting with using Ajax to load all images from a local folder onto my HTML page. The code I am referring to comes from this question. I am running the files on a (Tomcat 8.5) server in Eclipse and opening the URL in Google Chrome. However, when ...

Embed full content in iframe using bootstrap 4

Embedding an iframe of an appointment scheduling frontend on my page has been a challenge. While the width is correct, the height of the frame is too small. Despite attempting various CSS modifications, I have not been able to achieve the desired result. I ...

Utilize Angular to initiate the transmission of attribute values upon a click event

My question may be simple, but I've been struggling to find an answer. How can I send attributes or item property bindings of an item through a click event in the best way? For example: <item class="item" [attr.data-itemid]="item.id ...

Challenging design with CSS shapes

Can this specific shape be created using just one HTML element? I am looking to use it for image cropping purposes, so having only one element would make the process easier ...

Unable to retrieve angular HTML content from my standard HTML website

I have a basic HTML website and I am looking to redirect to an Angular website upon clicking a button on the HTML site. Both the HTML website and Angular build are hosted on the same server, Hostinger. The button in question is here: This is the simple HT ...

What's the best way to update the value of a TextInput field?

Previously, I was updating the text input using local state. Here's an example: state = {name: ''} ... <AddEditFormInputs onChangeText={name => this.setState({ name })} textStateValue ...

What is the best way to receive a user's input date in Dynamics 365 using HTML/JavaScript?

My HTML webform is set up to capture user input like address, card number, city, and state in text format. However, within Microsoft Dynamics 365, I have a custom entity with fields for this information. When a user completes the webform and submits it, a ...

Incorporate a fontawesome icon into a dynamically created button using ajax

Is it possible to insert fontawesome icons into a button created using this code snippet? $.each(response, function (i, item) { trHTML += '<tr><td>' + item.name + '</td><td>' + "<input type='button&apo ...

Managing JavaScript promise rejections

What is the best approach to managing an error, such as the one labeled "new error" in the code snippet below, that occurs outside of a promise? function testError() { throw new Error("new error") // How can this error be properly handled? var p ...

Retrieving selected values from a dynamic Primeng checkbox component

Within my Angular app, I am managing an array of questions. Each question includes a text field and an array of string options to choose from. The questions are retrieved dynamically from a service and can be updated over time. To allow users to select mul ...

Only display the child component once the asynchronous function in the parent's mounted hook has finished executing

In my coding setup, there is a parent component that is responsible for rendering a child component. The challenge I am currently facing involves making an asynchronous call (specifically an axios 'get' request from Vuex actions) inside the mount ...

Constantly positioning the text cursor over the Textbox

I am currently in the process of developing a webpage that will feature only one text box for displaying information based on the input data provided. Our strategy involves utilizing either a Barcode Scanner or Magnetic Swipe as well as a Touch Screen Moni ...

The ES6 reduce method is not giving the expected result

In Image 1, the output you will see if you log the final array from Snippet 1. My goal is to transform my array to match the format shown in Image 2. I attempted using lodash's _.uniqBy() method [Snippet 2], but the logged output of the reduce varia ...