FileUpload Example -- Source Code

HTML Page -- index.htm

<!DOCTYPE html>

<!-- FileUpload Example
Source code file: styles.css
Upload the Kids JSON file from computer
harddrive. Then look up gender and age
for a requested name. -->

<html lang="en">
    <head>
        <title>FileUpload Example</title>
        <script src="script.js"></script>
        <link rel="stylesheet" href="styles.css">
    </head>

    <body>
        <h1>FileUpload Example</h1>

        <label for="file">
            Upload JSON Input File:
        </label><br>
        <input type="file" id="file"><br><br>

        <label for="name">Enter Name:</label><br>
        <input type="text" id="name"><br><br>

        <button id="btn">
            Get Kid Information
        </button><br><br>

        <p id="output">Kid Information:<br></p>
    </body>
</html>

CSS Page -- styles.css

/* FileUpload Example
   Source code file: styles.css
   Upload the Kids JSON file from computer
   harddrive. Then look up gender and age
   for a requested name. */

*    { font-family: Helvetica, Arial, 
       sans-serif; }
body { background-color: #E0E0FF; }
img  { width: 100px; height: 100px;
       padding: 5px; margin: 5px; }

Script Page -- script.htm

// FileUpload Example
// Source code file: styles.css
// Upload the Kids JSON file from computer
// harddrive. Then look up gender and age
// for a requested name.

// Define contents as a global variable.
var contents;

function readSingleFile(event) {

    // Obtain the single uploaded file.
    var f = event.target.files[0]; 

    if (f) {
        var r = new FileReader( );
        r.onload = function(e) { 
            contents = e.target.result;
        }
        r.readAsText(f);
    }
    else { 
        alert("Failed to load file");
    }
}

function clickEventHandler( ) {
    var txtField = document.getElementById("name");
    var requestedName = txtField.value;
    var kidsArray = JSON.parse(contents);
    for(var k of kidsArray) {
        if (requestedName == k.name) {
            output = `Name: ${k.name}; ` +
               `Gender: ${k.gender}; ` +
               `Age: ${k.age} <br>\n`;

            // Break out of for loop.
            // When we find a match on name,
            // no need to keep looking.
            break;
        }
        else {
            output = `Name ${requestedName} ` +
                "not found<br>\n";
        }
    }

    // Display all outputs in paragraph.
    var para = document.getElementById("output");
    para.innerHTML += output;
}

// Attach event handlers.
function init( ) {

    // When file name in file upload element
    // changes, call the readSingleFile event handler.
    document.getElementById("file").
        addEventListener("change", readSingleFile, 
            false);

    // Attach click event handler for button.
    document.getElementById("btn").
        addEventListener("click", clickEventHandler)
}

window.addEventListener("load", init);

Input File -- kidsdata.json