Add Items to JavaScript Arrays

In this example below you will see how to do a Add Items to JavaScript Arrays with some HTML / CSS and Javascript

This small pen will add user input: First Name, and Last Name to two separate Javascript arrays, and display the data on the page.

Thumbnail
This awesome code was written by izotope115, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright izotope115 ©
  • HTML
  • CSS
  • JavaScript
      <form class="form-horizontal">
        <div class="form-group">
            <label for="inputFirstName" class="col-sm-2 control-label">First Name</label>

            <div class="col-sm-10">
                <input type="text" class="form-control" id="inputFirstName" placeholder="">
            </div>
        </div>
        <div class="form-group">
            <label for="inputLastName" class="col-sm-2 control-label">Last Name</label>
            <div class="col-sm-10">
                <input type="text" class="form-control" id="inputLastName" placeholder="">
            </div>
        </div>

        <div class="form-group">
            <div class="col-sm-offset-2 col-sm-10">
                <button type="button" class="btn btn-default" onclick="insert()">Submit</button>
            </div>
        </div>
    </form>

    <div>
        <ul class="list-group">
            <li class="list-group-item hide" id="results">
            </li>
        </ul>
    </div>

/*Downloaded from https://www.codeseek.co/izotope115/add-items-to-javascript-arrays-RGGyaG */
      body {
            margin: 20px;
        };
        .hide {
            display: none
        };
        .show {
            display: block
        };


/*Downloaded from https://www.codeseek.co/izotope115/add-items-to-javascript-arrays-RGGyaG */
      var fname = [];
        var lname = [];

        var inputFirstName = document.getElementById("inputFirstName");
        var inputLastName = document.getElementById("inputLastName");
        var results = document.getElementById("results");

        function insert() {
            if (inputFirstName.value || inputLastName.value != "") {
                fname.push(inputFirstName.value);
                lname.push(inputLastName.value);

                inputFirstName.value = "";
                inputLastName.value = "";
                results.innerHTML = "";

                $("li").removeClass("hide").addClass("show");
                results.innerHTML += "First Name: " + fname.join(', ') + "<br />"
                results.innerHTML += "Last Name: " + lname.join(', ') + "<br />"
            }
        }

Comments