Clone table with checkbox values

Asked

Viewed 70 times

1

Updated code. Edson Alves' help.

I’m having trouble calculating Total sum when unchecking the checkbox. At the moment I am checking, it calculates correctly, the problem is in the unchecking that should subtract.

$(".c").click(function() {

  var values = $(this).val().split('|');
  if ($(this).prop('checked')) {

    var quantity = $("table[id^=tabelaIE]").length;

    $(this).data('qty', quantity);

    var table = $("#tabelaIE").clone(true)
      .attr('id', function() {
        return this.id + quantity;
      })
      .find(':text,:file')
      .attr('id', function() {
        return this.id + quantity;
      })
      .val("")
      .end();
    //Adiciona valores 1|Taxa de locação|+|15.00|FIX|%|POR|VLT
    table.find('.tNome').text(values[1]);
    table.find('.tDias').text($("#dias").val());
    table.find('.tValor').text(values[3]);
    tTotal = values[3] * $("#dias").val();
    table.find('.tTotal').text(tTotal.toFixed(2));

    values.forEach(function(valor, index) {
      table.find('[class="split' + (index + 1) + '"]').val(valor)
    });

    table.appendTo('#abc');

    var oldVal = $('#somaTabelaIE').val();
    $('#somaTabelaIE').val(eval(oldVal || 0) + eval(tTotal))
  } else {
    var oldVal = $('#somaTabelaIE').val();
    $('#somaTabelaIE').val(oldVal - eval(tTotal))
    //remove a table que pertence ao checkbox
    $("table#tabelaIE" + $(this).data('qty')).remove()
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="hidden" id="dias" value="2">

<div id="abc">
  <div id="abc">
    <table id="tabelaIE" width='400' border='0'>
      <tr>
        <td class="tNome" width='164'></td>
        <td class="tDias" width='36' align='right'></td>
        <td class="tValor" width='53' align='right'></td>
        <td class="tTotal" width='119' align='right'></td>
        <td class="tValores">
          <input type="hidden" class="split1" value="">
          <input type="hidden" class="split2" value="">
          <input type="hidden" class="split3" value="">
          <input type="hidden" class="split4" value="">
          <input type="hidden" class="split5" value="">
          <input type="hidden" class="split6" value="">
          <input type="hidden" class="split7" value="">
          <input type="hidden" class="split8" value="">
        </td>
      </tr>
    </table>
    <br>
    Soma Total: <input type="text" name="somaTabelaIE" id="somaTabelaIE" value="">
  </div>
</div>


<fieldset class="scheduler-border">
	<legend class="scheduler-border">Impostos/Encargos</legend>
	
	<div id="D1">1. 
		<input name="opcoes[]" class="c obrigatorio" type="checkbox" value="1|Texto 1|+|15.00|FIX|%|POR|VLT" alt="+ 0.15 FIX %" title="Texto 1"> <b> Texto 1 </b>
		<input type="text" value="" class="i"> 
	</div>

	<div id="D2">2. 
		<input name="opcoes[]" class="c " type="checkbox" value="2|Texto 2|+|5.00|DIA||MON|DIA" alt="+ 5.00 DIA " title="Texto 2"> Texto 2
		<input type="text" value="" class="i">
	</div>
		
	<div id="D3">3. 
		<input name="opcoes[]" class="c " type="checkbox" value="3|Texto 3|+|30.00|FIX||MON|VLT" alt="+ 30.00 FIX " title="Texto 3"> Texto 3
		<input type="text" value="" class="i">
	</div>
		
	<div id="D4">4. 
		<input name="opcoes[]" class="c " type="checkbox" value="3|Texto 4|+|35,00|FIX||MON|VLT" alt="+ 35,00 FIX " title="Texto 4"> Texto 4
		<input type="text" value="" class="i">
	</div>
</fieldset>

  • Your question is not very clear, but if you just want to clone you can use the jQuery clone: $('.checkbox').clone(true). The true indicates that you want to clone along with your values

  • @edsonalves edited my code, I am not able to delete the table created by unchecking the checkbox. Know how to do?

  • you can use the function prop to determine if the checkbox is checked by clicking: $(this).prop('checked') and decide whether to remove or add

  • Your new problem is that when you enter the else the value tTotal does not exist. You can copy the line tTotal = values[3] * $("#dias").val(); into the else or throw it to before the if

1 answer

1


I think I finally understand your question, following modifications:

  $(".c").click(function(){
  			var values = $(this).val().split('|');
        //define se esta marcado ou não
        if($(this).prop('checked')){

           var quantity = $("table[id^=tabelaIE]").length;

           //adiciona o valor para identificar na hora de remover
           $(this).data( 'qty', quantity );

           // Clone the main table
           var table = $("#tabelaIE").clone(true)
           // Change its ID to the current ID plus the quantity variable
           .attr( 'id', function() { return this.id + quantity; })
           // find any text or file inputs
           .find( ':text,:file' )
           // change their IDs
           .attr( 'id', function() { return this.id + quantity; })
           // set the input values to ""
           .val( "" )
           // return to the cloned table
           .end();
           //adiciona valores ao texto dos td
           table.find('.nome').text(values[1]);
           table.find('.dias').text(values[2]);
           table.find('.valor').text(values[3]);
           table.find('.total').text((values[0]) * (values[3]));
           
           //adiciona valores nos inputs em suas posições
           values.forEach(function(valor, index){
           	table.find('[class="split'+(index+1)+'"]').val(valor)
           });
           
           
           // append wherever you want it.
           // As the comment below your question states,
           //   this is not a valid placement
           table.appendTo('#abc');
           var oldVal = $('#somaTabelaIE').val();
           $('#somaTabelaIE').val(eval(oldVal||0) + eval(values[3]))
        }else{
           var oldVal = $('#somaTabelaIE').val();
           $('#somaTabelaIE').val(oldVal - eval(values[3]))
           //remove a table que pertence ao checkbox
           $("table#tabelaIE"+$(this).data('qty')).remove()
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="abc">
	<table id="tabelaIE" width='400' border='0'>
		<tr>
		  <td class="nome" width='164'>Nome</td>
		  <td class="dias" width='36' align='right'>2</td>
		  <td class="valor" width='53' align='right'>60.00</td>
		  <td class="total" width='119' align='right'>120.00 <input type="text" name="opcoe[]" value="" style="width: 50px"></td>
      <td class="valores"> 
      <input type="text" class="split1" value="">
      <input type="text" class="split2" value="">
      <input type="text" class="split3" value="">
      <input type="text" class="split4" value="">
      <input type="text" class="split5" value="">
      <input type="text" class="split6" value="">
      <input type="text" class="split7" value="">
      <input type="text" class="split8" value=""></td>
		</tr>
     
	</table>

	<input type="text" name="somaTabelaIE" id="somaTabelaIE" value="">
</div>


<fieldset class="scheduler-border">
	<legend class="scheduler-border">Impostos/Encargos</legend>
	
	<div id="D1">1. 
		<input name="opcoes[]" class="c obrigatorio" type="checkbox" value="1|Texto 1|+|15.00|FIX|%|POR|VLT|1" alt="+ 0.15 FIX %" title="Texto 1"> <b> Texto 1 </b>
		<input type="text" value="" class="i"> 
	</div>

	<div id="D2">2. 
		<input name="opcoes[]" class="c " type="checkbox" value="2|Texto 2|+|5.00|DIA||MON|DIA" alt="+ 5.00 DIA " title="Texto 2"> Texto 2
		<input type="text" value="" class="i">
	</div>
		
	<div id="D3">3. 
		<input name="opcoes[]" class="c " type="checkbox" value="3|Texto 3|+|30.00|FIX||MON|VLT" alt="+ 30.00 FIX " title="Texto 3"> Texto 3
		<input type="text" value="" class="i">
	</div>
		
	<div id="D4">4. 
		<input name="opcoes[]" class="c " type="checkbox" value="3|Texto 4|+|35,00|FIX||MON|VLT" alt="+ 35,00 FIX " title="Texto 4"> Texto 4
		<input type="text" value="" class="i">
	</div>
</fieldset>

Also available in fiddle: https://jsfiddle.net/kndh7xw5/1/

  • And the part of the value and total sum, as it does to include in the table?

  • Where the value to be added should be picked up?

  • Each checkbox, within the value field, is like this 1|Texto 1|+|15.00|FIX|%|POR|VLT, I need to take each field of this separated by pippe, put in the created table, and also take all the separate data and put in a hidden input, to assemble the calculations and send to the BD.

  • with $('input').val().split('|') vc get an array with these values... But I didn’t understand what I meant by "the sum" which of the values should be summed?

  • I’ll explain...

  • In the pippe sequence, it looks like this: ID | Nome da Taxa | fator | valor | ..., there is already a variable that has contracted days that must be multiplied by the value $("#dias").val(). At the beginning of the table I left it filled with an example value.

  • see this image to see what it would look like http://prntscr.com/lmln4c

  • I modified the code by taking position 3 and adding, then subtracting when removing... Your first input was without ID, so I added 1 to avoid error. See if that’s what you needed Because I still don’t think I understand.

  • I’m gonna test.....

  • I updated my code, from a look at the table part, I put Ids and new fields. I think this is better to understand.

  • Good morning Edison, I updated the original code, I’m having difficulties calculating the sum total. What is wrong?

Show 7 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.