How Do I Access A Javascript Value Across Functions/variables?
Solution 1:
Are you looking for something like element properties? Mydiv.tax=taxvalue; Properties of Elements are an elegant way of communicating between different functions. You can assign any value to any element. You can retrieve the value from any function in JavaScript as long as the Basic element lives.
Solution 2:
One way you can do it is to set a global selectedCountryCode
variable inside your success callback, and reference tax_rates[selectedCountryCode]
in your TaxPrice array (which should be an object, as nnnnnn pointed out)
(function () {
var selectedCountryCode = "";
var onSuccess = function(x) {
var ip = x.traits.ip_address;
document.getElementById('ip_address').value = ip;
selectedCountryCode = x.country.iso_code; // <-- Set selectedCountryCode for later usedocument.getElementById('ip_country_code').value = selectedCountryCode; // <-- Set dropdown value
};
document.getElementById("ip_country_code").addEventListener("change", function() {
selectedCountryCode = this.value;
console.log(TaxPrice());
});
// Object of values for tax ratesvar tax_rates = {};
tax_rates["noteu"] = 0.0;
tax_rates["ES"] = 21.0;
tax_rates["AU"] = 20.5;
tax_rates["BE"] = 21.7;
functionTaxPrice() {
var taxprice = 0;
taxprice = tax_rates[selectedCountryCode];
return taxprice;
}
})();
Change Me: <selectid="ip_country_code"><optionvalue="noteu">noteu</option><optionvalue="ES">ES</option><optionvalue="AU">AU</option><optionvalue="BE">BE</option></select>
Solution 3:
So, thanks for your suggestions. Not sure if I understand how this is working exactly, but after some poking around, it now is. Compared to the code in the original question, I had to:
1) Add a global variable at the top, above everything else, unrelated to the IP lookup code (i.e. there is now no reference to country_tax
within the IP onSuccess
variable):
var country_tax;
2) Replace XXXXX in the TaxPrice function with:
var country_tax = document.getElementById("ip_country_code").value;
var taxprice = taxes_from_database[country_tax];
So the full TaxPrice function ends up as:
functionTaxPrice()
{
var taxprice = 0;
var country_tax = document.getElementById("ip_country_code").value;
var taxprice = tax_rates[country_tax];
return taxprice;
}
No need, it seems, for nested functions or closures or anything very complicated. It doesn't matter (to the code) if the tax_rates are set up as an array or an object, the outcome is the same, although I would like to understand why you recommend an object over an array in this case.
And—given TaxPrice gets the value from the form field and not from within the IP onSuccess function—I don't know why I need the global variable declaration at the top, if anyone wants to have a go at explaining that…
Post a Comment for "How Do I Access A Javascript Value Across Functions/variables?"