Get selected item value using a server side add bu

2019-09-03 13:07发布

Datatables Jquery server-side Sample Project Link:

Similar to this article but not using C#.

This code below correctly gets the correct price in the correct row.

   $(document).on('click','.add_btn',function (){
     var id = $(this).attr("id");

   var dataRow = $('#example').DataTable().row( id ).data();
   var price = dataRow[2];

So, I'd expect the answer to look something like:

 var qtd = dataRow[3];  //[3] because the select options is the next column
   var qtd_num = document.getElementById(qtd).selectedOptions[0].value; 

A confusing part is getting the element ID to plug it into the above formula. Because the id as of right now is meta.row using the datatables library (which may have to change?). Here is my full code:

<script type="text/javascript"> 
var numbers= [1, 2 , 3, 4];
$(document).ready(function() {
   var table=  $('#example').DataTable( {
        "processing": true,
        "serverSide": true,
        ajax: {
        url: 'server.php',
        type: 'POST',
        },
     columnDefs: [ 
         {  targets: -1,
         render: function (data, type, row, meta) {
            return '<button type="submit" class="add_btn btn btn-success btn-md active" data-id="' + meta.row + '"  id=" ' + meta.row + ' " value="add">  <span class="glyphicon glyphicon-plus"></span> </button>';
         }
         },
         {
            targets: -2,
            render: function (data, type, row, meta){
                                    var $select = $('<select data-id="' + meta.row + '"  id="' + meta.row + ' " ></select>', {
                                    });
                                    $.each(numbers, function (k, v, row, meta) {

                                        var $option = $("<option></option>", {

                                            "text": v,
                                            "value": v
                                        });
                                        if (data === v) {
                                            $option.attr("selected", "selected")
                                        }
                                        $select.append($option);
                                    });
                                    return $select.prop("outerHTML");
         }
        } ],
    })
} ); // end ready
</script>

1条回答
The star\"
2楼-- · 2019-09-03 13:55

var qtd = dataRow[3]; amounts to nothing because there is no [3] index in the data returned which is throwing an error.

An easier route to accessing the select in that row:

$(document).on('click','.add_btn',function (){
  var id = $(this).attr("id");
  var dataRow = $('#example').DataTable().row( id ).data();
  var price = dataRow[2];
  var qtd_num = $(this).closest('tr').find('select').val()
  ...
})
查看更多
登录 后发表回答