View Full Version : 'onclick' Storing Value Not Working

Aug 11th, 2015, 10:47 PM
so I have this <a> tag:

<a href="/book-testdrive" class="addtocart" value="YX57WDL" title="Book Test Drive">
<i class="glyphicon glyphicon-road"></i>
<span>&nbsp;Book Test Drive</span>
As you can see it is given a value of value="YX57WDL" now what I would like to do is capture that value when the a tag is clicked and placed into a variable.

There are many <a> tags on my page with many different values that are created dynamically. If a user presses another a tag I'd like it storing in the same variable but replace the value with that of the unique <a> tag value.

Also the variable needs to be stored site wide, I guess the solution to this would be Web Storage API.

So far I've tried using this Javascript:

var links = document.querySelectorAll('.addtocart ');

links.onclick = function(){
localstorage['storedValue'] = this.value ;
However when I console.log() the links variable it contains nothing.

Any idea why this might be happening?


Aug 12th, 2015, 03:17 AM
<a> tags don't have a value attribute - you should use one of the new data attributes such as data-value instead.
also with the code you are trying to use links is a nodelist and not a single element so to attach an onclick to it you'd use link[0].onclick link[1].onclick etc depending on how many elements have that class.

Old Pedant
Aug 12th, 2015, 05:31 PM
seems weird that you have something identified as ADD to cart but then your onclick will really do REPLACE cart contents.