【问题标题】:Store multiple inputs in JSON key as part of array在 JSON 键中存储多个输入作为数组的一部分
【发布时间】:2017-01-09 16:44:25
【问题描述】:

晚上好,

我正在尝试制作一个动态的表单,这意味着用户可以通过单击按钮添加一些<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-submit 一起使用

【问题讨论】:

  • 你在使用 jquery 吗?如何添加/更改这些输入?他们是否有能力随时更改/添加/删除?
  • 如果用户更改输入值,是否应该覆盖数组中的先前值?
  • 我正在使用angularjs,如果“表单”已经发送到后端,输入值不应该被覆盖
  • 您应该添加 angular 作为标签。这将改变您处理此问题的方式。在描述中还提到您正在使用 angular
  • @mnemosdev 是的,如果用户没有提交表单,并且在输入字段中将“a”更改为“b”,那么数组元素应该是“a”还是“b”?

标签: javascript html angularjs arrays json


【解决方案1】:

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

您需要在操作实际表单方面对您提供的各种功能进行一些测试,但这应该是一个很好的起点。

【讨论】:

    【解决方案2】:

    如果你给所有相关的输入同一个类,你可以使用getElementsByClassName(),然后循环遍历返回的数组,然后在创建一个canGoTo.push(elementArray[i].value)之后做一些事情空 canGoTo 数组。

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

    【讨论】:

      猜你喜欢
      • 2019-05-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-25
      • 1970-01-01
      • 2019-07-05
      • 1970-01-01
      • 2022-11-29
      • 2020-04-20
      相关资源
      最近更新 更多