Call a value from the BD to an input


Hello good afternoon I would like to know how I call this value 19 to another view in an input that I will put hidden, I need it to calculate the operation automatically the value 19 I have it in a table called Iva

and not having to put

    var iva = 19;
    var operacion = (subtotal*iva)/100;
    var total = operacion+subtotal;
asked by JOHAN ALEXIS MORENO GUISAO 06.07.2018 в 21:55

1 answer


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


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;
var iva = $("#tdIVA").text();
var operacion = (subtotal * iva) / 100;
var total = operacion + subtotal;
<script src=""></script>
    <td id="tdIVA">19</td>
<div class="preview-subtotal"></div>

<div class="preview-total"></div>
answered by 07.07.2018 / 01:30