How can I add a row via select box to datatable?

大城市里の小女人 提交于 2019-12-13 03:20:39

问题


I am adding a row to my datatables by selecting an option from my selectbox:

 <select class="item-select">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="vw">VW</option>
  <option value="audi">Audi</option>
</select>

 $(document).on('change', '.item-select', function() {
    var optionValue = $(this).val();
    var optionText = $('.item-select option[value="'+optionValue+'"]').text();
    table.row.add({
      "id":     optionValue,
      "name":   optionText,
    }).draw();

  });

It is working well, but I want to be able to add the same option directly once again. This means for example: I add Volvo, then I add Saab, but when I want to add now another Saab it is not working. I have to add something else like VW, and then I am able to add Saab.


回答1:


Add a blank value and reset the select which won't trigger the change event.

$(document).on('change', '.item-select', function() {
    var optionValue = $(this).val();
    var optionText = $('.item-select option[value="'+optionValue+'"]').text();
    if (optionValue) {
      //  table.row.add({
      //    "id":     optionValue,
      //    "name":   optionText,
      //  }).draw();
      $('option', this).first().prop('selected', true)
      console.log(`${optionText} added`)
    }
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select class="item-select">
  <option>Select make...</option>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="vw">VW</option>
  <option value="audi">Audi</option>
</select>


来源:https://stackoverflow.com/questions/54256159/how-can-i-add-a-row-via-select-box-to-datatable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!