简体   繁体   中英

Populate Bootstrap modal form fields from JSON

I've got a Bootstrap modal that displays a large form (30+ inputs).

I wrote the following code to populate the first few fields from 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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