Update a variable of a function called in "Onlick" using javascript variable

I have the following html in the body:

<a  onclick="popupCenter(address,'Title','500','500');" href="javascript:void(0);" id="myID">

which calls the following function:

    <script>
function popupCenter(url, title, w, h) {
var left = (screen.width/2)-(w/2);
var top = (screen.height/2)-(h/2);
return window.open(url, title, 'toolbar=no, location=no,directories=no, status=no, menubar=no, scrollbars=no, resizable=no,     copyhistory=no, width='+w+', height='+h+', top='+top+', left='+left);
} 
</script>

I need to replace the 'address' variable of the called function under onclick option with a javascript variable (say variable x below):

<script type="text/javascript">
var x = "NewURL"
</script>

Now the catch is: There are many instances wherein popupCenter is being called. And also, the variable x is being decided through the values of a dropdown. Each instance of popupCenter call is updated with a unique address (which is deduced using the value obtained from the dropdown). So, I really can't make the url static.

There are 3 variables like x, each of which is a URL which is created using a value obtained from a dropdown. Each created URL is now supposed to be passed to the address/url of popupcenter called in three different instances.

And before any change is made to dropdown, there remains a fixed value of address in each popupCenter function call (referred to as address here). It is that address variable which needs to be changed with the variables created in javascript dynamically.

It would be great if one could help. I'm not good at web development.

Upvotes: 0

Views: 38

Answers (1)

epascarello
epascarello

Reputation: 207501

Instead of using url, use x since it is a global and you can reference it in your function.

window.open(x, title, .... )

Other option is to just change the onclick to use the variable x

onclick="popupCenter(x,'Title','500','500');"

Quick demo without window.open, just a console line to show that referencing the variable after you update it will update inside the function.

var base = "TEST";
var x = "1";

function test1 (y) {
    console.log(base + " : " + y);
}

function test2 () {
    console.log(base + " : " + x);
}


function updateX () {
    x = new Date().toLocaleString();  //just generate something to test  
}
<a href="#" onclick="test1(x)">Test test1(x)</a>
<a href="#" onclick="test2()">Test test2()</a>

<button onclick="updateX()">Update X</button>

Upvotes: 2

Related Questions