动态形式相关下拉列表

时间:2018-09-23 16:33:02

标签: arrays forms dynamic dropdown

我找到了解决方案,所以我共享代码来运行动态表格,每行中都有依赖列表(填充槽阵列)。

Working Fiddle

jQuery(function($) {
 var i = parseInt($("tr:last td:first").attr("id"));
 $("#add").on("click", function (e) {
  i++;
  var tr = '<tr id="row'+i+'">'+
   '<td><select class="custom-select form-control form-control-sm typ" id="typ'+i+'" name="typ[]"><option value="" selected="selected">Sélectionner</option></select></td>'+
   '<td><select class="custom-select form-control form-control-sm mdl" id="mdl'+i+'" name="mdl[]"><option value="" selected="selected">Sélectionner</option></select></td>'+
   '<td><input type="text" class="form-control form-control-sm" name="cod[]" placeholder="Code barre"></td>'+
   '<td><button type="button" class="btn btn-sm btn-danger btn_remove" id="'+i+'"><i class="fa fa-times" aria-hidden="true"></i></button></td>'+
   '<td>'+i+'</td>'+
   '</tr>';
  $("#materiel").append(tr);
  var tbl_row = $(this).closest('tr');
  var id = i;
  $('#ndx').val(id);
  loadmat(id);
 });
 $(document).on('click', '.btn_remove', function(){  
  var button_id = $(this).attr("id");   
  $('#row'+button_id+'').remove();  
 });
});
$(document).ready(function() {
 var typ = document.getElementById("typ1"),
  mdl = document.getElementById("mdl1");
 for (var vtyp in matObject) {
  typ.options[typ.options.length] = new Option(vtyp, vtyp);
 }
 typ.onchange = function () {
  mdl.length = 1;
  if (this.selectedIndex < 1) return;
  var vmdl = matObject[this.value];
  for (var i = 0; i < vmdl.length; i++) {
   mdl.options[mdl.options.length] = new Option(vmdl[i], vmdl[i]);
  }
 }
});
function loadmat(id) {
 var typ = document.getElementById('typ'+id),
 mdl = document.getElementById('mdl'+id);
 for (var vtyp in matObject) {
  typ.options[typ.options.length] = new Option(vtyp, vtyp);
 }
 typ.onchange = function () {
  mdl.length = 1;
  if (this.selectedIndex < 1) return;
  var vmdl = matObject[this.value];
  for (var i = 0; i < vmdl.length; i++) {
   mdl.options[mdl.options.length] = new Option(vmdl[i], vmdl[i]);
  }
 }
}

我找到了更好的解决方案,更清晰易读 所以我和别人分享 谢谢!

0 个答案:

没有答案