如何填充物化模态中的键值对

时间:2018-05-14 11:09:39

标签: jquery html bootstrap-modal

我试图在点击按钮上填充模态的键和值,我无法填充。

我正在尝试获取除“modelname”之外的modelinfo(JSON)。我希望所有的键和值都填充在模态上。但在这里我只能获得最后的价值。

这是我的代码:

$('.addAttribute').click(function() {
  if (deviceIdStatus === 'old') {
    var getModelDetails = ajaxServices("/getServices/models", "GET");
    console.log(JSON.stringify(getModelDetails));
    $('#modelName').val(getModelDetails[0].modelinfo.modelname).attr('disabled', 'disabled');
    $.each(getModelDetails, function(i, el) {
      $.each(el.modelinfo, function(key, val) {
        if (key != "modelname") {
          console.log(key + ":" + val);
          $(".addModel").trigger("click");
        };
        $.each(el.modelinfo, function(key, val) {
          if (key != "modelname") {
            console.log(key + ":" + val)
            $(".modelAttribute").val(key);
            $(".modelType").val(val);
          }
        });
      })
    })
  }
});

点击addAttribute按钮,我在模态上获取键值。但我到处都只得到最后一个价值。我正在检查基于deviceId。如果deviceId是旧的,则模型在数据库中具有键和值。我无法从数据库中获取值。我正在使用orientdb。

这是JSON,我试图填充除modelname

之外的modelinfo
[{
  "@type": "d",
  "@class": "models",
  "templateId": "#31:0",
  "modelinfo": {
    "modelname": "obdDataModel",
    "temp": "2",
    "hum": "1",
    "co": "0"
  },
  "deviceid": "ANX2345613",
  "@rid": "#39:0",
  "@version": 9
}]

以下是我的输出结果,输出只填充了最后一个键值:

Output

1 个答案:

答案 0 :(得分:0)

问题出在这里。

$(".modelAttribute").val(key);
$(".modelType").val(val);

jQuery类选择器将更改所有元素的值。

你是否准确写出了这样的内容容器的数量?

<!-- div 1 -->
<div>
  <input type="text" class="modelAttribute" />
  <input type="text" class="modelType" />
</div>
<!-- div 2 -->
<div>
  <input type="text" class="modelAttribute" />
  <input type="text" class="modelType" />
</div>
<!-- div 3 -->
<!-- div 4 -->

你应该像这样编码:

  $.each(el.modelinfo, function(key, val) {
    if (key != "modelname") {
      // create element
      var template = `
        <div>
          <input type="text" class="modelAttribute" value="${key}" />
          <input type="text" class="modelType" value="${value}" />
        </div>
      `;
      $("#bigContainerWhatever").append(template);
    }
});