question about adding dropdown to edit button on click

question about adding dropdown to edit button on click

phong123phong123 Posts: 1Questions: 1Answers: 0
edited August 2021 in DataTables 1.10

Can anyone tell me I want to add dropdown to the table when I click edit but now I'm getting an error that when I click edit, it creates 2 other cells and in the dropdown box, I can't write the value I selected, please help me

my code

<script>

var index = 0;
$('[data-toggle="tooltip"]').tooltip({
    boundary: "window",
    container: "body"
});
var actions = `<a class="add" title="Confirm" data-toggle="tooltip"><i class="fa fa-check"></i></a>
           <a class="edit" title="Edit" data-toggle="tooltip"><i class="fas fa-edit"></i></a>
           <a class="delete" title="Delete" data-toggle="tooltip"><i class="fa fa-trash"></i></a>`;

var dataTable = $('#table-id').DataTable({
    select: 'multi',
    dom: 'lfrtBip',
    "paging": true, // false to disable pagination (or any other option)
    "ordering": false, //disable ordering
    "scrollY": "300px",
    "scrollCollapse": true,
    buttons: [
        'copy', 'csv', 'excel', 'pdf', 'print'
    ]
});

var data1 = ["1", "2"];
for (let index = 0; index < data1.length; index++) {
    dataTable
        .row.add(["1", "1", data1[index], actions])
        .draw()
        .node();
}
dataTable.draw();
var c=0;
// //grab all the unique sorted data entries from the necessary row
const category = dataTable.column(2).data().unique().sort();
// //Row click handler
// console.log(dataTable.on('deselect', (event, row, type, index) => writeCell($(row.node()).find('select'))));
// dataTable.on("select", (event, row, type, index) => {
//    $(row.node())
//       .find("td:eq(2)")
//       .html(
//          "<select>" +
//             category.reduce(
//                (options, item) =>
//                   (options += `<option value="${item}" ${item == row.data().category? 'selected' : ''}>${item}</option>`),
//                ""
//             ) +
//             "</select>"
//       );
//       console.log(row.data().category+"b");
// });
dataTable.on('deselect',(event, row, type, index) => {
        c=0;
        writeCell($(row.node()).find('select'))
})
//Drop down menu stop event propagation
$('#table-id').on('click', 'tbody td select', event => event.stopPropagation());
// $('#table-id').on('click', 'tbody td select', event => {event.stopPropagation();console.log("a")});
//Write dropdown value into table
var writeCell = dropdown => {
    const currentRow = dataTable.row(dropdown.closest('tr'));
    const rowData = currentRow.data();
    rowData.category = dropdown.val();
    currentRow.remove();
    dataTable.row.add(rowData).draw();
    c=rowData.category;
};

$('.table-add').click(function () {
    
    $(this).attr("disabled", "disabled");
    var row = '<tr class="hide">' +
        '<td><input type="text" class="form-control" name="name" id="name"></td>' +
        '<td><input type="text" class="form-control" name="department" id="department"></td>' +
        '<td><input type="text" class="form-control" name="phone" id="phone"></td>' +
        '<td><input type="text" class="form-control" name="name" id="name"></td>' +
        '<td><input type="text" class="form-control" name="department" id="department"></td>' +
        '<td>' + actions + '</td>' +
        '</tr>';
    dataTable.row.add($(row)).draw();
    $("table tbody tr").eq(index).find(".add, .edit").toggle();
    index += 1;
    $('[data-toggle="tooltip"]').tooltip({
        boundary: "window",
        container: "body"
    });;
});

// // Add row on add button click
$(document).on("click", ".add", function () {
    var empty = false;
    var input = $(this).parents("tr").find('input[type="text"]');
    input.each(function () {
        if (!$(this).val()) {
            $(this).addClass("error");
            empty = true;
        } else {
            $(this).removeClass("error");
        }
    });
    $(this).parents("tr").find(".error").first().focus();
    if (!empty) {
        input.each(function () {
            $(this).parent("td").html($(this).val());
        });
        $(this).parents("tr").find(".add, .edit").toggle();
        $(".add-new").removeAttr("disabled");
    }
    // Remove input-box row and put value row
    $(this).tooltip('hide');
    var lastHTML = '<tr>' + $(this).parents("tr").html() + '</tr>';
    dataTable.row($(this).parents("tr")).remove();
    dataTable.row.add($(lastHTML)).draw();
});
// grab all the unique sorted data entries from the necessary row
$(document).on("click", ".edit", function(){
    $(this)
      .parents("tr")
      .find("td:eq(2)")
      .html(
         "<select>" +
            category.reduce(
               (options, item) =>
                  (options += `<option value="${item}"? 'selected' : ''}>${item}</option>`),
               ""
            ) +
            "</select>"
      );

      $(this)
      .parents("tr")
      .find("td:not(:last-child):not(:nth-last-child(2))")
      .each(function () {
          c=0;
         $(this).html(
            '<input type="text" class="form-control" value="' +
               $(this).text() +
               //         category.reduce(
               //            (options, item) =>
               //               (options += `<option value="${item}"? 'selected' : ''}>${item}</option>`),
               //            ""
               //         ) +
               '">'
         );
      });
    $(this).parents("tr").find(".add, .edit").toggle();
    $(".add-new").attr("disabled", "disabled");
    
 });


// Delete row on delete button click
$(document).on("click", ".delete", function () {
    $(this).tooltip('hide');
    dataTable.row($(this).parents("tr")).remove().draw();
    $(".add-new").removeAttr("disabled");
    index -= 1;
});

</script>

Edited by Colin - Syntax highlighting. Details on how to highlight code using markdown can be found in this guide.

Answers

  • colincolin Posts: 15,142Questions: 1Answers: 2,586

    That's a lot of code. We're happy to take a look, but as per the forum rules, please link to a test case - a test case that replicates the issue will ensure you'll get a quick and accurate response. Information on how to create a test case (if you aren't able to link to the page you are working on) is available here.

    Cheers,

    Colin

Sign In or Register to comment.