user3278038 user3278038 - 6 months ago 22
jQuery Question

How to store a value from an HTML input field in a javascript array?

I would like to know how to store a value from an HTML input field after a button is clicked into a JavaScript array and then how to display that array data to the screen.

Thank you, below is my html code :

<!DOCTYPE HTML>

<html>
<head>
<title>Checklist</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
</head>
<body>

<input type="text" id="item" placeholder="Enter an item">
<button id="add">Add Item</button>

</body>
</html>

Answer

You can create an array, at click of button, push input type="text" element value to array; use window.open() data URI of type application/octet-stream to download file. To update existing file, you can include <input type="file"> element for user to upload same file which was downloaded, push current input type="text" value to same file, then prompt user to download original file with same name. Though note, it is user decision to download file.

See also Edit, save, self-modifying HTML document; format generated HTML, JavaScript

<!DOCTYPE HTML>
<html>
<head>
    <title>Checklist</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
  <script>
    $(function() {
      var input = $(":text");
      var button = $("button");
      var arr = [];
      button.click(function() {
        arr.push(input.val());
        input.val("");
        window.open("data:application/octet-stream," + JSON.stringify(arr));

      })
    })
    </script>
</head>
<body>  

    <input type="text" id="item" name="save" placeholder="Enter an item">
    <button id="add">Add Item</button>

</body>
</html>

plnkr http://plnkr.co/edit/cQZznvyltX46UO1Y0lDG?p=preview