Skip to content Skip to sidebar Skip to footer

How Do I Change Html Label Text Once File Has Been Selected Using Javascript

Thanks for viewing my question. I have a form below that has a file input field. Safe to say I have hidden this input field, and am now using the label as the primary 'button' to s

Solution 1:

You can use the javascript onchange event to detect when the value of the #profilepic input changes.

When it does, you can capture the new value of the #profilepic input and replace the text of the label with that value.

Example:

var profilePic = document.getElementById('profilepic'); /* finds the input */

function changeLabelText() {
    var profilePicValue = profilePic.value; /* gets the filepath and filename from the input */
    var fileNameStart = profilePicValue.lastIndexOf('\\'); /* finds the end of the filepath */
    profilePicValue = profilePicValue.substr(fileNameStart + 1); /* isolates the filename */
    var profilePicLabelText = document.querySelector('label[for="profilepic"]').childNodes[2]; /* finds the label text */
    if (profilePicValue !== '') {
        profilePicLabelText.textContent = profilePicValue; /* changes the label text */
    }
}

profilePic.addEventListener('change',changeLabelText,false); /* runs the function whenever the filename in the input is changed */
<div class="changepic-wrap">
<form action="changepicauth.php" method="post">
<input type="file" name="profilepic" id="profilepic" class="inputfile">
<br>
<label for="profilepic">
<img src="/images/profile/upload.png" />
Upload Picture...
</label>
<br>
<div class="button-wrap">
<button>Change Picture</button>
</div>
</form>
</div>

Solution 2:

You can use change event, select element having for attribute value equal to event.target: #profilepic element id, set the .innerHTML of selected element to event.target.files[0] .name

document.getElementById("profilepic")
.addEventListener("change", function(e) {
  document.querySelector("[for=" + e.target.id + "]")
  .innerHTML = e.target.files[0].name;
})
.inputfile {
  width: 0.1px;
  height: 0.1px;
  opacity: 0;
  overflow: hidden;
  position: absolute;
  z-index: -1;
}
<!-- Change Picture Form -->
<div class="changepic-wrap">
  <form action="changepicauth.php" method="post">
    <input type="file" name="profilepic" id="profilepic" class="inputfile">
    <br>
    <label for="profilepic">
      <img src="/images/profile/upload.png" />Upload Picture...
    </label>
    <br>
    <div class="button-wrap">
      <button>Change Picture</button>
    </div>
  </form>
</div>

Post a Comment for "How Do I Change Html Label Text Once File Has Been Selected Using Javascript"