在JSON键阵列

问题描述:

晚安的一部分存储多个输入,在JSON键阵列

我试图做一个形式,是动态的,这意味着有些<input>标签可以通过用户与一个按钮的点击添加。这样的行为可以轻松地通过javascript完成,每当用户感觉喜欢它时添加一个元素,并将其附加到父元素,在这种情况下是表单。

input标签的动态特性来自需要在数组内部存储一堆值的必要性,该数组必须稍后在mongodb文档中进行推送,并且未设置元素的数量,因此具有动态特性。一个例子,以说明我的意思:

<form> 
    <fieldset> 
     <legend>Username and ID</legend> 
     <input type="text" name="username" /> 
     <input type="text" name="uniqueId" /> 
    </fieldset> 

    <fieldset> 
     <legend>Places the user can go to</legend> 
     <input type="text" /> <!-- user input would be "pub" --> 
     <input type="text" /> <!-- user input would be "market" --> 
     <input type="text" /> <!-- user input would be "cinema" --> 
     <input type="text" /> <!-- user input would be "computer store" --> 

     <!-- other elements, added dynamically --> 
     <!-- the user might be able to go also to the gym, or the park, 
      he is the one that decides the number of places to add to the 
      input --> 
    </fieldset> 
</form> 

我想的事情是这个输入值存储一起数组这已经是一个对象的一部分,像这样里面:

myObject = { 
    username: "Ryan", 
    uniqueId: "A001", 
    canGoTo : [ 
     "pub", 
     "market", 
     "cinema", 
     "computer store", 
     ...other inputs that the user might have added and wrote] 
} 

canGoTo键将填充用户在该表单的各种输入内插入的值。我会如何将它们存储在数组canGoTo

编辑:我使用AngularJS与NG-提交

+0

你使用jQuery吗? 这些输入将如何添加/更改?他们是否有能力随时更改/添加/删除? – Ishey4

+0

如果用户改变一个输入值,如果数组中的先前值被覆盖? – guest271314

+0

我使用的是angularjs,输入值不应该被覆盖,如果“表单”已经发送到后端已经 – mnemosdev

您可以使用ng-model来定位数组的特定索引。喜欢的东西:

<form> 
    <fieldset> 
     <legend>Username and ID</legend> 
     <input type="text" name="username" /> 
     <input type="text" name="uniqueId" /> 
    </fieldset> 

    <fieldset> 
     <legend>Places the user can go to</legend> 

     <input type="text" ng-repeat="input in myObject.canGoTo" 
       ng-model="myObject.canGoTo[$index]" /> 
    </fieldset> 
</form> 

要添加新的输入:

$scope.myObject.canGoTo.push (''); 

你需要运行您在操作的实际形式方面提供的各种功能的测试,但是这应该是一个良好的发射点。

如果你把所有的相关输入同一个类,你可以使用getElementsByClassName方法(),然后循环返回数组,并做沿东西线canGoTo.push(elementArray [i] .value)创建一个空的canGoTo数组后。

如果您想一次添加一个,您需要添加的只是一个变量,用于跟踪当前输入的索引编号。