当我动态添加选择框时,所选插件不起作用

时间:2019-08-07 08:33:03

标签: jquery jquery-chosen

当我动态添加一行时,Chosen插件不适用于新的选择框。如何将选择功能添加到新的选择框?

var sayac = 6;
$(document).ready(function(){
$(document).on('click', '.addd', function(){
  var html = '';
  sayac += 1;
  html += '<tr>';
  html += '<td><select name="kagit_tip[]" class="select form-control inst_amount' + sayac + '"><option value="">Kağıt Tipi</option><?php echo fill_unit_select_box($connect); ?></select></td>';
  html += '<td><select name="kagit_ebat[]" class="select form-control inst_amount' + sayac + '"><option value="">Kağıt Ebadı</option><?php echo kagit_ebat_selectbox($connect); ?></select></td>';
  html += '<td><input type="text" name="tabaka[]" class="form-control item_quantity inst_amount' + sayac + '" " /></td>';
  html += '<td><input type="text" name="kgfiyati[]" class="form-control item_quantity inst_amount' + sayac + '" " /></td>';
  html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';  
  $('#item_table').append(html);
});
<div class="col-md-12">
  <form method="post" id="insert_form">
    <div class="table-repsonsive">
      <span id="error"></span>
      <table class="table table-bordered" id="item_table">
        <tr>
          <th>Ek Kağıt</th>
          <th>Ebat</th>
          <th>Tabaka</th>
          <th>Kg Fiyatı</th>
          <th>Ek Kağıt Tutar</th>
          <th><button type="button" name="addd" class="btn btn-success btn-sm addd"><span class="glyphicon glyphicon-plus"></span></button></th>
        </tr>
      </table>
    </div>
  </form>
</div>

1 个答案:

答案 0 :(得分:0)

大概是您在页面加载时正在调用chosen(),因此该页面仅适用于DOM中的select元素。

要解决您的问题,您需要针对动态添加的新元素再次调用chosen(),如下所示:

var sayac = 6;

$(document).ready(function() {
  $(document).on('click', '.addd', function() {
    sayac++;

    var html = '';
    html += '<tr>';
    html += '<td><select name="kagit_tip[]" class="select form-control inst_amount' + sayac + '"><option value="">Kağıt Tipi</option><?php echo fill_unit_select_box($connect); ?></select></td>';
    html += '<td><select name="kagit_ebat[]" class="select form-control inst_amount' + sayac + '"><option value="">Kağıt Ebadı</option><?php echo kagit_ebat_selectbox($connect); ?></select></td>';
    html += '<td><input type="text" name="tabaka[]" class="form-control item_quantity inst_amount' + sayac + '" " /></td>';
    html += '<td><input type="text" name="kgfiyati[]" class="form-control item_quantity inst_amount' + sayac + '" " /></td>';
    html += '<td><button type="button" name="remove" class="btn btn-danger btn-sm remove"><span class="glyphicon glyphicon-minus"></span></button></td></tr>';

    var $row = $(html).appendTo('#item_table');        
    $row.find('select').chosen({
      // your options here...
    });
  });
});

还要注意,增量id / class属性是一种反模式,我建议您删除它。