2017-01-09 69 views
-1

晚安的一部分存儲多個輸入,在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

回答

2

您可以使用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 (''); 

你需要運行您在操作的實際形式方面提供的各種功能的測試,但是這應該是一個良好的發射點。

1

如果你把所有的相關輸入同一個類,你可以使用getElementsByClassName方法(),然後循環返回數組,並做沿東西線canGoTo.push(elementArray [i] .value)創建一個空的canGoTo數組後。

如果您想一次添加一個,您需要添加的只是一個變量,用於跟蹤當前輸入的索引編號。