简体   繁体   English

从JSON填充Bootstrap模态表单字段

[英]Populate Bootstrap modal form fields from JSON

I've got a Bootstrap modal that displays a large form (30+ inputs). 我有一个Bootstrap模态,可以显示大表格(30多个输入)。

I wrote the following code to populate the first few fields from JSON. 我编写了以下代码来填充JSON的前几个字段。

$('#seg-detail-modal').on('shown.bs.modal', function (e) {

  var modal = $(this);

  $.get( "includes/segdata.json", function( data ) {
    $('#seg-detail-modal').find("input[name='segCode']").val(data.segCode);
    $('#seg-detail-modal').find("input[name='orgName']").val(data.orgName);
    $('#seg-detail-modal').find("input[name='referenceId']").val(data.referenceId);
  });

});

Is there a more efficient way of populating a large form than what I'm doing here? 有没有比我在这里做的更有效的填充大表格的方法?

You could just iterate through the object properties and match selector to property in that loop. 您可以仅遍历对象属性,然后将选择器与该循环中的属性匹配。

Something like: 就像是:

$('#seg-detail-modal').on('shown.bs.modal', function(e) {
  var $inputs = $(this).find(':input');
  $.getJSON("includes/segdata.json", function(data) {
    $.each(data, function(key, val) {
      $inputs.filter('[name="' + key + '"]').val(val);
    });
  });
});

If a property exists that doesn't have a match the selector will just fail quietly 如果存在一个不匹配的属性,则选择器只会安静地失败

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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