简体   繁体   中英

How to get the data of a row if a checkbox is checked

I have a function that returns the values ​​of a row, but I can not separate them and put them inside different parameters.

function guardarImpuestos() {
  $('input[type=checkbox]').each(function() {
    if ($(this).is(':checked')) {
      //test
      console.log($(this).closest("tr").children("td").get()[0]);
      console.log($(this).closest("tr").children("td").get()[1]);
      console.log($(this).closest("tr").children("td").get()[2]);
      //end test
      var $row = $(this).closest('tr');
      $('td', $row).each(function(i) {
        var abc = $(this).text();
        console.log(abc);
      })
      var parametros = {
        "cuit": $("#cuit").val(),
        "impuesto": i need the first val here,
        "concepto": and second here
      };
      $.ajax({
        data: parametros,
        url: 'api/insertar_impuestos.php',
        type: 'post',
        success: function(response) {
          alert("Impuesto agregado.");
        }
      });
    }
  });
}

You can loop over each <td> element in the row and put the text from each one into an array. Then you can access those text elements using array notation values[0] , etc.

function guardarImpuestos() {

$('input[type=checkbox]:checked').each(function () {

  var $row = $(this).closest('tr');
  var values = [];

  $('td', $row).each(function(i){
      values.push( $(this).text() );
  })
  var parametros = {

    "cuit" : $("#cuit").val(),
    "impuesto" : values[0],
    "concepto" : values[1]
  };

  $.ajax({

      data:  parametros,
      url:   'api/insertar_impuestos.php',
      type:  'post',
      success:  function (response) {
              alert("Impuesto agregado.");
      }

  });

});

}

An alternate way to do it, if you have a small, determined number of cells, is to skip the $('td',$row).each( function and just do something like:

...
var parametros = {
    "cuit" : $("#cuit").val(),
    "impuesto": $('td',$row).eq(0).text(),
    "concepto": $('td',$row).eq(1).text()
}
...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM