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

2019-08-19 13:30发布

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条回答
我命由我不由天
2楼-- · 2019-08-19 13:43

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>

查看更多
登录 后发表回答