Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access the Javascript variable value outside the script tag

I want to access the Javascript variable value outside the Javascript tag.

function getprices(input) {
    return input.match(/[0-9]+/g);
}
var subtotals = get_getprices('%GLOBAL_OrderTotal%');
var Grand_total = subtotals[0];
<img height="0" width="0" border="0" src="http://testing.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=I want the Grand+Total Value here">
like image 420
Rav Avatar asked Feb 10 '23 00:02

Rav


2 Answers

You'd need to update the src property on that img element. Let's suppose you gave the img an id (you don't have to, there are other ways to select it, but I'm keeping it simple):

<img id="the-image" height="0" width="0" border="0" src="http://testing.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=I want the Grand+Total Value here">

Then:

function getprices(input) {
    return input.match(/[0-9]+/g);
}
var subtotals = getprices('%%GLOBAL_OrderTotal%%'); // <=== Changed to `getprices`, was `get_getprices`
var Grand_total=subtotals[0];
var img = document.getElementById("the-image");
img.src = "http://testing.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=" + Grand_total;

It looks like Grand_total will always be a number, but for the general case where it might not be, , be sure to use encodeURIComponent (it doesn't do any harm even if it is a number):

img.src = "http://testing.com?merchantId=M1&orderNo=%%GLOBAL_OrderId%%&saleAmount=" + encodeURIComponent(Grand_total);

If you didn't use an id on the img, that's fine, you can use any CSS selector via document.querySelector. That's supported by all modern browsers, and also IE8.


Note that there are other issues with that code, though, not least that getprices looks fairly suspect.

like image 114
T.J. Crowder Avatar answered Feb 12 '23 12:02

T.J. Crowder


All you need to do is to assign your value to src of img in your javascript

$("#imgNeeded").attr("src",".../"+Globalvalue)

As T.J. Crowder said. make sure you encode URI if your variable contain something other than number

like image 43
user786 Avatar answered Feb 12 '23 13:02

user786