There are several ways to obtain the value of an element. The most direct and safe is giving a id
to that element in the HTML and then recovering its value based on the id that has been given.
Suppose that the td
where is the VAT we give the id tdIVA
in this way:
<td id="tdIVA">19</td>
Then you can recover its value in a variable by:
var iva = $("#tdIVA").text();
In jQuery, the elements are reached by their id by putting the sign of #
before the id, therefore: #tdIVA
. Another thing, text()
is used because the td
is not an element that the user can modify directly as a input
, if it were a input
it would be preferable to use val()
instead of text()
.
In pure Javascript this would be done as follows:
var elIVA = document.getElementById("tdIVA");
var valorIVA=elIVA.textContent; //navegadores modernos
Or:
var valorIVA=elIVA.innerText; //otros navegadores
Notice that a reference to the element is first created with document.getElementById
and then that reference is used. It is a recommended practice, although it can also be done directly like this:
var valorIVA=document.getElementById("tdIVA").textContent;
The result would be the same.
There are other ways to access the elements, if you do not have an id. In the case of not being able to modify your table, you can access the value of that td
in several ways. For example: reaching the first td
of the first row of the table X
(in case the table does have an id); or, reaching the first td
of the first row of the first table of the DOM (in case the table does not have id and there is more than one table in your document). If that were the case, comment on it and I'll show you examples of how to do it this way.
Here is a fragment of the test code. I hope you find it useful.
var subtotal = 87 //Valor hipotético;
$(".preview-subtotal").text(subtotal);
var iva = $("#tdIVA").text();
console.log(iva);
var operacion = (subtotal * iva) / 100;
var total = operacion + subtotal;
$(".preview-operacion").text(operacion);
$(".preview-total").text(total);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td id="tdIVA">19</td>
</tr>
</table>
<h4>Sub-Total</h4>
<div class="preview-subtotal"></div>
<h4>Total</h4>
<div class="preview-total"></div>