0

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>
empiric
  • 7,825
  • 7
  • 37
  • 48
Alexander
  • 29
  • 1
  • 6

1 Answers1

1

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

Community
  • 1
  • 1
guest271314
  • 1
  • 15
  • 104
  • 177
  • Sorry, I changed the question from saving into a file, to, into an array. – Alexander May 30 '16 at 23:39
  • @user3278038 Yes, `javascript` at post achieves this. You can remove `window.open("data:application/octet-stream," + JSON.stringify(arr));` portion. `arr` should contain value of `#item` element pushed to `arr` array at each click on `button` element – guest271314 May 30 '16 at 23:41
  • @user3278038 See updated plnkr http://plnkr.co/edit/cQZznvyltX46UO1Y0lDG?p=preview – guest271314 May 30 '16 at 23:50
  • this is great! How can it be changed to display each item in the array inside of an HTML list? Thanks. – Alexander May 31 '16 at 00:07
  • @user3278038 _"How can it be changed to display each item in the array inside of an HTML list?"_ You can append the item in the array to the list item – guest271314 May 31 '16 at 00:17