如何通过选择框向数据表添加行? [英] How can I add a row via select box to datatable?

查看:120
本文介绍了如何通过选择框向数据表添加行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过从选择框中选择一个选项在数据表中添加一行:

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();

  });

它运行良好,但是我希望能够再次直接添加相同的选项. 例如,这意味着:我添加Volvo,然后添加Saab,但是当我现在想添加另一个Saab时,它不起作用.我必须添加其他内容,例如VW,然后才能添加Saab.

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.

推荐答案

添加一个空白值并重置不会触发change事件的选择.

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>

这篇关于如何通过选择框向数据表添加行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆