Forum Moderators: open

Message Too Old, No Replies

Global variable

javascript global variable

         

OrlandoM

6:00 pm on Jan 8, 2010 (gmt 0)

10+ Year Member



Merry Christmas to all.
The aim is to store id of tag <td> in global variable to restore innerHTML of it. For example when you click on a link inside <td> the content of it is changed to form with <input type="text"> for quantity of items to be added (I'm developing online store) to shopping cart and <input type="submit">. And then if user clicks on another link inside another <td> the content of the previous <td> is changed to link again. I've read if declare variable without keyword var it is assigned as global, but this is not working. (I'm using createElement and appendChild with innerHTML since pure innerHTML is not supported novadays with XHTML).

My snippet of JS which is half working (can not restore innerHTML of remtd (previous <td>))

function showCart(id) {
if(typeof( oldid ) != 'undefined') {
remtd = document.getElementById(oldid);
remtd.removeChild(remtd.childNodes[0]);
var nestdiv = document.createElement("div");
nestdiv.innerHTML = "<a rel='noindex, nofollow' class='basket-add'><span><span>To basket</span></span></a>";
remtd.appendChild(nestdiv);
} else {
oldid = id;
}
var partId;
partId = id.match(/\d+/, id);
var td;
td = document.getElementById(id);
td.removeChild(td.childNodes[0]);
var newdiv = document.createElement("div");
newdiv.innerHTML = "<form action='addtocart.php' method='GET'>Кол-во: <input class='quant' type='text' name='quantity'><br /><input type='hidden' name='url' value='"+location.href+"'><input type='hidden' name='id' value='"+partId+"'><input class='proceed' type='submit' name='go' value='Ok'></form>"
td.appendChild(newdiv);
oldid = id;
}

Maybe someone knows how make it working? Thanks beforehands.

OrlandoM

6:07 pm on Jan 8, 2010 (gmt 0)

10+ Year Member



Checked in Firefox (great!) it's working, maybe Opera didn't refresh cache with my function

daveVk

11:20 am on Jan 9, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



oldid needs to hold its value between calls to showCart (global var ?)
on the other hand remtd seems only to be used locally.

I've read if declare variable without keyword var it is assigned as global

Rather than relying on this, explicitly declaring global's makes your intent a lot clearer

eg
var oldid = null; // declare global
function showCart(id) {
if( oldid != null ) {

It is not clear how persistent you need oldid to be, if you need it to persist between page loads, consider keeping it as form data or cookie.