Datatables jQuery Select

217 views Asked by At

I have a problem with the selects in jQuery DataTables. The first page loads the selections well but the second does not. Sometimes it loads them, others not

$.ajax({
  type: "POST",
  url: "Compensaciones.aspx/getTipoConceptoComp",
  data: "{p_IdTipoTributo: '" + $("#<%=ddlTipoTributo.ClientID %>").val() + "'}",
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: function(data, st) {
    if (st == 'success') {
      if (data.d.length > 0) {
        dropdownlist = $('#Detalledet select').empty().append('<option selected="selected" value="0">SELECCIONE</option>')[i];
        $.each(data.d, function() {
          dropdownlist = $('#Detalledet select').append($("<option value=" + this['IDTIPOCONCEPTO'] + "></option>").val(this['IDTIPOCONCEPTO']).html( /*this['CONCEPTO'] + " - " + */ this['DESCRIPCION'] + "  " + this['IMPACTO']))[i];
        });
      } else {
        dropdownlist = $('#Detalledet select').empty().append('<option selected="selected" value="0">Not available<option>')[i];
      }
    }
  },
  failure: function(data) {
    alert(data.d);
  }
});
2

There are 2 answers

0
Luciano Gaitan On BEST ANSWER

I was able to solve it by calling the function in the drawcallback of the table thanks to all who took the trouble to answer

0
Mark Schultheiss On

I am assuming the issue is the object being sent so I create one called mydata. Then using the promise form of .ajax I create a local array, then hit the DOM only one time with that.

  • No need for .empty() since either way we replace it with .html()
  • cache the selected dropdown list/select in let dropdownlist = $('#Detalledet select'); so we can manipulate it without hitting the DOM multiple times to get it
  • push new options to an array (couple ways to do this)
  • once done append the array hitting the DOM once instead of each loop
  • Caveat: I have not taken time to test this with an actual set of data since no example was supplied

let mydata = {
  p_IdTipoTributo: $("#<%=ddlTipoTributo.ClientID %>").val()
};
.ajax({
    type: "POST",
    url: "Compensaciones.aspx/getTipoConceptoComp",
    data: mydata,
    contentType: "application/json; charset=utf-8",
    dataType: "json"
  })
  .done(function(data) {
      let dropdownlist = $('#Detalledet select');
      if (data.d.length > 0) {
        let newOptions = [];
        .push($('<option selected="selected">', {
            value: 0
          })
          .text("SELECCIONE"));
        $.map(data.d, function(n, i) {
          options.push($('<option>', {
              value: n['IDTIPOCONCEPTO']
            })
            .text(n['DESCRIPCION'] + "  " + , n['IMPACTO']));
        });
        dropdownlist.html(newOptions);
      } else {
        dropdownlist.html('<option selected="selected" value="0">Not available</option>');
      }
    }
  })
.fail(function(data) {
  alert(data.d);
});