J. Robinson J. Robinson - 3 months ago 16
HTML Question

How to Change Label Text upon File being Selected within Form using Javascript

thank you for taking a look at my question.

I asked a question similar to this before hand at the link below. Unfortunately, the answer given works in the code snippet but not on my site. I created a blank HTML document and inserted the following code into it. The basics of what i'm trying to do is this. The file input tag will be hidden using CSS. I'm then using the label tag to take over control of the input tag. Once a file is selected i want the file name (not path) to be displayed within the label and also keep the image visible to the user as well. As previously stated in my last question I do NOT wish to use jQuery. Thanks in advance for taking a look at my code and helping out!

Heres my previous question: How do I change HTML Label Text Once File Has Been Selected using Javascript

Heres the code in my 'index2.php' file:

<html>
<head>
<script>
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 */
</script>
</head>
<body>
<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="#" />
Upload Picture...
</label>
<br>
<div class="button-wrap">
<button>Change Picture</button>
</div>
</form>
</div>

</body>
</html>

Answer

Place the <script>...</script> at the very end of the document, just before </body>.

That way, all of the DOM will already have loaded and you won't need to listen for an onload or an onDOMContentLoaded event.