Uncaught Referenceerror: hr_tb is not defined

Asked

Viewed 41 times

-1

I’m having problems with my Javascript.

Basically, I get input values at the push of a button. I used the jquery plugin Mask to add masks, but at the time of storing the results, I change the mask to be able to account for the value, after storing, I change the mask to the previous one only by the look.

In jquery I take the input value and call another function to make a calculation.

(I will put the js incomplete pq is very large, but it works, I added this Mask Feature now and I’m having this prolema.

function test(){
$(document).ready(function (){
    $("#VH").unmask();
    $('#VH').mask('000.00');
    var vl_hr = document.getElementById("VH").value;
    $('#VH').mask('R$:000.00');
    var hr_tb = document.getElementById("HT").value;
    calcular();
});
}


function calcular() {

  var salario_bruto = hr_tb * vl_hr;

If you need any more information, I’ll be available.

Console error:

  • Uncaught Referenceerror: hr_tb is not defined
  • at calculate (js.js:31)
  • At Htmldocument. (js.js:24)
  • at j (jquery-1.11.3.min. js:2)
  • At object.add [as done] (jquery-1.11.3.min. js:2)
  • at m.fn.init.m.fn.ready (jquery-1.11.3.min. js:2)
  • at test (js.js:18)
  • At Htmlanchorelement.onclick (VM378 html2.html:67)

Edit: the value of the HT id element is being stored in var hr_tb (I checked and the value can be stored, but the error persists).

2 answers

0

Guys, I just did a little digging, and I saw that a var is limited to its scope, not a whole file. So the solution I found was this:

var hr_tb = 0;
var vl_hr = 0;

function calcular() {

  $(document).ready(function (){
      $("#VH").unmask();
      $('#VH').mask('000.00');
      var vl_hr = document.getElementById("VH").value;
      $('#VH').mask('R$:000.00');
      var hr_tb = document.getElementById("HT").value;
    })


  var salario_bruto = hr_tb * vl_hr;

0

The variable hr_tb only has scope within the function of $(document).ready. By the way, it makes no sense to put the event .ready within a function, as this event is triggered when the DOM is loaded. You are making inappropriate use of the event.

If you want the variable hr_tb has value within the function calcular(), you have two options:

1) Define it as a global variable: just take the var, leaving only hr_tb = document.getElementById("HT").value;.

2) Send as a parameter to the function calcular() (most recommended):

function test(){
   ...
   var hr_tb = document.getElementById("HT").value;
   calcular(hr_tb);
}

function calcular(hr_tb) {
   ...
}

Browser other questions tagged

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