Home > Mobile >  Basics to JavaScript (getElementbyID)
Basics to JavaScript (getElementbyID)

Time:11-04

I'm new to JavaScript and I've been struggling with this problem for a while now. How can I use a variable from a JS file in another HTML file. I have a index.js file where my function is defined. It pulls data from Firebase and I want to use it in another HTML file where it has a script portion.

Index.js file:

async function readProjectNames() {
    const q = query(collection(db, "Projects"));
    var ProjectNames = [];
    const querySnapshot = await getDocs(q);
    querySnapshot.forEach((doc) => {
      // doc.data() is never undefined for query doc snapshots
      ProjectNames.push(doc.data().Name); 
    });
    document.getElementById("Projects").innerHTML = ProjectNames;
}
readProjectNames();

my HTML file:

 <!-- Add hours form -->
    <form name="AddHoursForm">
        <b> Select Project: </b>
        <select id="ProjectList">
            <option> --Choose Project-- </option>
        </select>
        <b> Select Engineer: </b>
        <select id="EngineerList">
            <option> --Choose Engineer-- </option>
        </select>

        <label for="HoursWorked"><b>Hours Worked: </b></label>
        <input id="HoursWorked" type="text">
        <button >Add Hours</button><br><br><br><br>
    </form>
<script>
//Populate Project List Drop-Down 
        var ProjectNames = [];
        ProjectNames = document.getElementById("Projects");
        console.log(ProjectNames);
  
        for (var i = 0; i < ProjectNames.length; i  ) {
            var Plist = document.createElement("option");
            var POpt = ProjectNames[i];
            Plist.textContent = POpt;
            Plist.value = POpt;
            PSelect.appendChild(Plist);
        }
</script>

How do I use ProjectNames array in my HTML file to populate my drop-down list? I can display the text using ID in HTML but I'm not able to use it in my script as a variable to populate my dropdown list. Any help would be appreciated. Thank you

CodePudding user response:

You could do

Index.js file:

async function readProjectNames() {
    const q = query(collection(db, "Projects"));
    var ProjectNames = [];
    const querySnapshot = await getDocs(q);
    querySnapshot.forEach((doc) => {
      // doc.data() is never undefined for query doc snapshots
      ProjectNames.push(doc.data().Name); 
    });
    return ProjectNames;
}

Then HTML file:

<html>
<head>
   <script src="index.js"></script>
</head>
<body>
<!-- Add hours form -->
    <form name="AddHoursForm">
        <b> Select Project: </b>
        <select id="ProjectList">
            <option> --Choose Project-- </option>
        </select>
        <b> Select Engineer: </b>
        <select id="EngineerList">
            <option> --Choose Engineer-- </option>
        </select>

        <label for="HoursWorked"><b>Hours Worked: </b></label>
        <input id="HoursWorked" type="text">
        <button >Add Hours</button><br><br><br><br>
    </form>
<script>
//Populate Project List Drop-Down 
        var ProjectNames = readProjectNames();
        console.log(ProjectNames);
  
        for (var i = 0; i < ProjectNames.length; i  ) {
            var Plist = document.createElement("option");
            var POpt = ProjectNames[i];
            Plist.textContent = POpt;
            Plist.value = POpt;
            PSelect.appendChild(Plist);
        }
</script>

CodePudding user response:

Sorry for such a late reply. I've read through the posts and all the comments. @anaconda I wasn't aware that was the way to do it but it makes sense how that works. In my case I can't import that index.js file as it gives me a 404 error probably due to the fact I'm running it on a local host. I can use the static method to import it but it was too complicated for me to understand right now so I went with the basic route which might be wrong.

@Scott Same answer as I gave above. I didn't want to go that route because that would make my code very complicated as I'm trying to understand the basics.

@Dave I wanted to do that way as well but I always got an error that the file not was present as I'm using local host and it doesn't locate the files in another folder. If that worked than Anaconda's way would've worked as well.

Thank you for your replies everyone.

I got it solved this way:

My Function in HTML script:

  function AddProjectToList(CName) {
            var ProjectNames = [];
            ProjectNames = CName.split(" ");
            console.log(ProjectNames);
            var PSelect = document.getElementById("ProjectLists");

            for (var i = 0; i < ProjectNames.length; i  ) {
                var Plist = document.createElement("option");
                var POpt = ProjectNames[i];
                Plist.textContent = POpt;
                Plist.value = POpt;
                PSelect.appendChild(Plist);
            }
        }

        function AddProjectNamesToList(TheProjects) {
            TheProjects.forEach(element => {
                AddProjectToList(element.Name);
            });
        }

My function in Index.js:

async function readProjectNames() {
    const querySnapshot = await getDocs(collection(db, "Projects"));
    var ProjectNames = [];
    querySnapshot.forEach(doc => {
      // doc.data() is never undefined for query doc snapshots
      ProjectNames.push(doc.data()); 
    });
    AddProjectNamesToList(ProjectNames);
}

I'm not sure if this is the correct way to do it but it does work. Thank you for all your help.

  • Related