简体   繁体   中英

Adding input to an array or object one-by-one using a form in Javascript

I want to know what code to use to create a form where the user can input something and click submit (or a button) and the data will be stored in an array (or JSON object) , then they can do it again and the previous data will be "pushed" hence the user can keep adding to it. This would continue so on and so forth. I am also interested if "local storage" can be used to store this information on the users machine.

This question is a continuation of a question I had here: Add form input to array with javascript using unshift()

Below is some code. This code does what I want but only with one input item.

Thank you.

<form>
<input id="input" type="text"/>
<button id="button"> Click me </button>
</form>


<script>

var input = document.getElementById("input"); // save the object
var button = document.getElementById("button");

var myArray = [];




button.onclick = function alerted (){
    myArray.unshift(input.value); // get the value
    alert(myArray);
    return false;
};


</script>​

Create a customs object like this:

 function MyObject(value1,value2,value3,value4,value5){
     this.attribute1=value1;
     this.attribute2=value2;
     this.attribute3=value3;
     this.attribute4=value4;
     this.attribute5=value5;
  }

Then use this object to store the individual values. Finally you can add this object in your array as below(one of the few patterns):

button.onclick = function alerted (){
      // get several input values and set in the custom object
      Myobject object = new MyObject(input1.value, 
                               input2.value,
                               input3.value,
                               input4.value,
                               input5.value);
      myArray.unshift(object); 
      alert(myArray);
      return false;
 };

Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM