How do I autofill a form based on the name of a file in javascript?

I have created a form in HTML which asks a user to upload a file. What I want to do is grab the name of this file, let’s say it is named something like name_456_031421.mp4, and split up the file name by each “_” and then auto-populate that into the input fields of the form. Then all of this information will be submitted to a database.

Example of file:

Upload File: name_456_031421.mp4 Gate: name Code: 456 Area: 031421

The issue I’m having is I can’t seem to even grab the name of the file and I’m not sure where to go from there with the rest of the task since I’m pretty new to JS and the other resources I’ve looked up don’t seem to be quite what I’m looking for to go about this task. I’d appreciate any advice with this code so far and any tips on how to further approach the rest of this issue. Thank you!

This is my HTML form:

<form method = "post" action = "../PHPDATABASE/vid-upload.php" enctype="multipart/form-data"> 
Gate:
<label for = "code"> Code:</label>   
<input type = "text" name = "code" />

<label for = "area"> Type: </label>
<input type = "text" name = "area" /> </form>

This is my javascript code so far to grab the file name:

var input = document.getElementById( 'form-upload-name' );
var infoArea = document.getElementById( 'uploaded-filename' );

console.log(input);
console.log(infoArea);

input.addEventListener( 'change', showFileName );

function showFileName( event ) {
  
  var input = event.srcElement;
  
  var fileName = input.files[0].name;
  
  infoArea.textContent = 'File name: ' + fileName;
  console.log(infoArea);
}

Answer

You could use the files method on the target property of an event object to get the files information.

const uploadInput = document.querySelector("#upload-input");
const codeInput = document.querySelector("#code");
const areaInput = document.querySelector("#area");

uploadInput.addEventListener('change', e => {
  // METHOD 1
  // const name = e.target.value;
  // console.log( name );

  // METHOD 2 RECOMMENDED
  // e.target.files contains info of the selected files
  const file = e.target.files;
  // To grab first file info
  const firstFileInfo = file[0];
  const nameOfFile = firstFileInfo.name;
  const getNameWithoutExtension = nameOfFile.split(".")[0];
  const [name, code, area] = getNameWithoutExtension.split("_");

  codeInput.value = code;
  areaInput.value = area;
})
    <label for="upload-input">Select a file:</label>
    <input type="file" id="upload-input" name="myfile">

    <label for = "code"> Code:</label>
    <input type = "text" name = "code" id="code"/>

    <label for = "area"> Type: </label>
    <input type = "text" name = "area" id="area"/>

Leave a Reply

Your email address will not be published. Required fields are marked *