Validate dynamic table sums in Javascript

Asked

Viewed 229 times

3

I have a question about validating sums of dynamic tables. I have two inputs one with the value with Iva and the other of the value without Iva. I have a dynamic table where I enter billing periods. When placing the total value with Iva it has to add all values with Iva entered in the table. I can only do this with values with Iva. how do I do for values without Iva? I don’t know how to do. Thank you!

<script language="JavaScript" type="text/javascript">
	function addRow(tableID) {
		var table = document.getElementById(tableID);
		var rowCount = table.rows.length;
		var row = table.insertRow(rowCount);
		var colCount = table.rows[0].cells.length;
		for(var i=0; i<colCount; i++) {
			var newcell	= row.insertCell(i);
			newcell.innerHTML = table.rows[0].cells[i].innerHTML;
			//alert(newcell.childNodes);
			switch(newcell.childNodes[0].type) {
				case "text":
					newcell.childNodes[0].value = "";
					break;
				case "checkbox":
					newcell.childNodes[0].checked = false;
					break;
				case "select-one":
					newcell.childNodes[0].selectedIndex = 0;
					break;
			}
		}
	}
	function deleteRow(tableID) {
		try {
			var table = document.getElementById(tableID);
			var rowCount = table.rows.length;
			for(var i=0; i<rowCount; i++) {
				var row = table.rows[i];
				var chkbox = row.cells[0].childNodes[0];
				if(null != chkbox && true == chkbox.checked) {
					if(rowCount <= 1) {
						alert("Não é possível apagar todas as linhas da tabela.");
						break;
					}
					table.deleteRow(i);
					rowCount--;
					i--;
				}
			}
		}catch(e) {
			alert(e);
		}
	}
	var quant_civa = document.getElementsByName("valor_afaturar_civa[]");
	var quant_siva = document.getElementsByName("valor_afaturar_siva[]");
	var teste = [];
	teste = dataString.split(",");
	function verifica(){
		var designacao_prest_serv = f.designacao_prest_serv.value;
		var fk_obra = f.fk_obra.value;
		var valor_total_civa = f.valor_total_civa.value;
		var valor_total_siva = f.valor_total_siva.value;
		var fk_subcontratado = f.fk_subcontratado.value;
		
		if (designacao_prest_serv == '' || designacao_prest_serv == ' '){
			alert ("Preencha a designação da prestação de serviços");
			designacao_prest_serv.focus();
			return false;
		}
		if (fk_subcontratado == '0') {
			alert ("Selecione um subcontratado");
			return false;
		}
		else{
			var soma_civa = 0;
			for (var i=0; i<quant_civa.length; i++){
				teste[i] = parseFloat(quant_civa[i].value);
				soma_civa += parseFloat(teste[i])			
			}
			if (soma_civa == valor_total_civa){
				return true;				
			}
			else{
				alert('A soma dos períodos de faturação não corresponde ao valor da Prestação de Serviços');
				return false;
			}

		}
	}
	function habilitar(){
	if(document.getElementById('obra').checked){
		document.getElementById('fk_obra').disabled = false;
		document.getElementById('fk_obra').value = 'obra';

	} else{
		document.getElementById('fk_obra').disabled = true;
		document.getElementById('fk_obra').value = '';

	}
}
</script>
<?php 	$sql = "SHOW TABLE STATUS LIKE 'adicionais_contrato'";
		$resultado = mysqli_query($link,$sql);
		$linha = mysqli_fetch_array($resultado);
		$idd = $linha['Auto_increment']; ?>
<h2>Criar Prestação de Serviços - Subcontratados</h2>
<form name="f" action="enviar_criar_adicional.php?id=<?php echo $idd; ?>" method="post" >
	<strong>Designa&ccedil;&atilde;o da prestação de serviços:</strong><br />
	<input id="designacao_prest_serv" type="text" size="100" name="designacao_prest_serv" maxlength="150" required/></br></br>
	<strong>Subcontratados:</strong>
	<select name="fk_subcontratado" id="fk_subcontratado">
	<option value="0">Selecione...</option>
	<?php $query_subcontratado = mysqli_query($link,"SELECT * FROM subcontratados ORDER BY nome ASC");
	while($subcontratado = mysqli_fetch_array($query_subcontratado)) { ?>
		<option value="<?php echo $subcontratado['id'] ?>" title="<?php echo $subcontratado['nome'] ?>"><?php echo $subcontratado['nome']; ?></option>
<?php } ?>
	</select><br><br>
	<label style="cursor: pointer;">
	<input type="radio" name="custos" id="custos_gerais" value="custos_gerais" onclick="habilitar();" checked  /> <strong>Custos Gerais</strong></label>
	<label style="cursor: pointer;">
	<input type="radio" name="custos" id="obra" value="obra" onclick="habilitar();"/> <strong>Obra</strong></label><br>
	<select name="fk_obra" id="fk_obra" disabled required>
		<option value="0">Selecione a obra...</option>
		<?php $query_prefixo = mysqli_query($link,"SELECT * FROM prefixos ");
		while($prefixo = mysqli_fetch_array($query_prefixo)) { 
			$query_obra = mysqli_query($link,"SELECT * FROM obras WHERE fk_prefixo=".$prefixo['id']." ORDER BY abrev_ano ASC, num_sequencial ASC");
			while($obra = mysqli_fetch_array($query_obra)) { 
				$id_obra = $obra['id'];?>
				<option value="<?php echo $obra['id'] ?>" title="<?php echo $obra['designacao'] ?>"><?php echo "O".$prefixo['tipo'].$obra['abrev_ano'].".".$obra['num_sequencial'].".".$obra['abrev_designacao']; ?></option>
			<?php
			}
		} ?>
	</select>
	<?php $data_abertura = date('Y-m-d'); ?>
	<br><br><strong>Data de abertura: </strong><?php echo $data_abertura ?><br /><br />
	<strong>Valor Total da Prestação de Serviços<br> Com IVA: </strong><input type="text" name="valor_total_civa" id="valor_total_civa" required/>
	<strong>Sem IVA: </strong><input type="text" name="valor_total_siva" id="valor_total_siva" required/><br /><br />
	<strong>Periodos de Fatura&ccedil;&atilde;o:</strong><br>
	<INPUT type="button" value="Adicionar linha" onclick="addRow('dataTable')" />
	<INPUT type="button" value="Apagar Linha" onclick="deleteRow('dataTable')" />
	<TABLE id="dataTable">
		<TR>
			<TD width="20px;"><INPUT type="checkbox" name="chk"/></TD>
			<TD width="100px;"><INPUT type="date" min="<?php echo date('Y-m-d'); ?>" id="data_afaturar" name="data_afaturar[]" required/></TD>
			<TD>Com IVA:<input type="text" name="valor_afaturar_civa[]" id="valor_afaturar_civa[]" value="0.00" required>€</TD>
			<TD>Sem IVA:<input type="text" name="valor_afaturar_siva[]" id="valor_afaturar_siva[]" value="0.00" required>€</TD>
		</TR>
	</TABLE>
	<p><input type="submit" onClick="return verifica()" value="Criar Prestação de Serviços"></p></br>
</form> 

  • I’m a little confused with your code. Mainly because it is divided into parts and in the latter it seems that values and objects appear from nowhere. Could you show the code that works with VAT values? This would make it easier to work with VAT-free.

  • Why can’t you do it with values without Iva? What error is happening?

  • I’ve already put all the code... I just can’t do for the other field without VAT..

1 answer

1


Try adding the following function CalcularValoresSemIVA(), calculating the total of all items named valor_afaturar_siva[], in your add and delete lines functions:

function CalcularValoresSemIVA(){
  var TotalValoresSemIVA = 0;
  for(i=0;i<document.getElementsByName("valor_afaturar_siva[]").length;i++){
    TotalValoresSemIVA += eval(document.getElementsByName("valor_afaturar_siva[]")[i].value);
  }
  alert("Total dos valores sem IVA: " + TotalValoresSemIVA + "€");
}

Edited:

If you want to have the value before testing the validations just do something like this:

function verifica(){
  /*
    No início da tua função verifica() que é chamada
    ao clicar em "Criar Prestação de Serviços" usas
    o meu código para obteres a variável com o valor
  */
  var TotalValoresSemIVA = 0;
  for(i=0;i<document.getElementsByName("valor_afaturar_siva[]").length;i++){
    TotalValoresSemIVA += eval(document.getElementsByName("valor_afaturar_siva[]")[i].value);
  }
  /*
    Depois fazes o que quiseres com a variável
    TotalValoresSemIVA nas validações abaixo
  */
}

Last code:

var Total = 0;
for(i=1; i<9; i++) {
  var NumAleatorio = Math.random().toFixed(2);
  document.write("Número " + i + " = " + NumAleatorio + "<br>");
  Total += eval(NumAleatorio);
}
document.write("Total sem toFixed(2) = " + Total);
document.write("<br>");
document.write("Total com toFixed(2) = " + Total.toFixed(2));

  • Where do I call this function?

  • 1

    I didn’t answer right away because I went to lunch. Add/declare this function and call it for example at the beginning of your function addRow(tableID) and at the end of deleteRow(tableID). Then just modify/remove the codic line with the alert(...); and do whatever you want with the variable TotalValoresSemIVA.

  • But if it’s just a billing period, I won’t add or delete line, so I won’t call the function... I’ve tried to put inside the if (soma_civa == valu_total_civa){ Calcularvaloressemiva(); } Because only when you have these equal values can I proceed.

  • A "billing period"? Not without quite what you mean by that. When do you want me to update the value, which is updating from x to x time, when a certain button is clicked, at some event or when one of the values changes? I can explain to you pretty much any of the options, I just don’t really know which one you want.

  • I want when you click "Create Service Provider" it validates the values. sum all the values of the billing periods (dynamic table) and confirm that it is equal to the one placed in the input. This for both VAT and VAT-free values

  • Check the code I added/edited to my reply.

  • Thanks and sorry for the inconvenience =) It worked!

  • It’s okay, happy to help. :)

  • Hello, I noticed that now I have a problem with the decimals. For example when we add 2.02 + 2.02+2.02 the total is 6.060000000005. I wanted it to only use up to 2 decimal places. I have tried with Eval(Document.getElementsByName("valor_afaturar_siva[]")[i].value). toFixed(2); but the value that gives the sum is 02.022.022.02€. How do I?

  • @Joanaaguide, see the last code in my answer. The toFixed(2) seems to be working well. Try applying it to the variable TotalValoresSemIVA at the end of the cycle for. Usa toFixed(2) in the account result.

  • Thanks =) It worked!

  • @Joanaaguida: Cool.

Show 7 more comments

Browser other questions tagged

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