1

I am trying to create a wish list for my products, I have a button with the same ID number of the product for wish list and I want when the user clicks on the button, it brings the data name value of the product that match with the ID number. this is my HTML :

<html>
<div>
    <ul>
        <li><a class="add-to-cart" href="#" data-name="Apple" data-id="1" data-price="1.22" >Apple $1.22</a><button onclick="myFunction()" data-id="1">Try it</button></li>
        <li><a class="add-to-cart" href="#" data-name="Banana" data-id="2" data-price="1.33">Banana $1.33</a><button onclick="myFunction()" data-id="2">Try it</button></li>
        <li><a class="add-to-cart" href="#" data-name="Shoe" data-id="3" data-price="22.33">Shoe $22.33</a><button onclick="myFunction()" data-id="3">Try it</button></li>
        <li><a class="add-to-cart" href="#" data-name="Frisbee" data-id="4" data-price="5.22">Frisbee $5.22</a><button onclick="myFunction()" data-id="4">Try it</button></li>
    </ul>
</div>
<html>

this is my Javascript code:

<script>
function myFunction() {
    var x = document.getElementsByClassName("add-to-cart")[0].getAttribute("data-name");
    document.getElementById("show-fav").innerHTML = x;
}
</script>

my code only brings the name apple when clicking any of the buttons.

any help will be appreciate it. thanks

charlie97
  • 51
  • 1
  • 11

3 Answers3

1

        var wishlist = Array(10);
    $(document).ready(function(){
      //wishlist = JSON.parse($.cookie('wishlist') || '{}');
      wishlist = JSON.parse(localStorage.getItem("wishlist") || '{}');
      if(wishlist != null){
      $.each(wishlist, function(index, name){
            $('#wishlist').append($('<li>').val(index).text(name));
        });    
      }
      else
        wishlist = {};
    });


    function myFunction(selectedElement) {
        var data_id = selectedElement.getAttribute("data-id");
        var data_name = $(".add-to-cart[data-id *= "+data_id+" ]").attr('data-name');
      if(!wishlist.hasOwnProperty(data_id)){
        wishlist[data_id] = data_name;
        $('#wishlist').append($('<li>').val(data_id).text(data_name));
        //$.cookie('wishlist', JSON.stringify(wishlist));
        localStorage.setItem("wishlist",JSON.stringify(wishlist));
        //document.cookie = (wishlist);
        console.log($.cookie('wishlist'));
        console.log(wishlist);
      }
      else{
    $('#wishlist li[value *= '+data_id+']').remove();
    delete wishlist[data_id];
    localStorage.setItem("wishlist",JSON.stringify(wishlist));
  }        
        //alert('Element already present');
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
<html>
<div>
    <ul>
        <li><a class="add-to-cart" href="#" data-name="Apple" data-id="1" data-price="1.22" >Apple $1.22</a><button onclick="myFunction(this)" data-id="1">Try it</button></li>
        <li><a class="add-to-cart" href="#" data-name="Banana" data-id="2" data-price="1.33">Banana $1.33</a><button onclick="myFunction(this)" data-id="2">Try it</button></li>
        <li><a class="add-to-cart" href="#" data-name="Shoe" data-id="3" data-price="22.33">Shoe $22.33</a><button onclick="myFunction(this)" data-id="3">Try it</button></li>
        <li><a class="add-to-cart" href="#" data-name="Frisbee" data-id="4" data-price="5.22">Frisbee $5.22</a><button onclick="myFunction(this)" data-id="4">Try it</button></li>
    </ul>
</div>
  <ul id="wishlist">
  </ul>
<html>

It is getting only apple because in following code you are using [0] index which is apple.

var x = document.getElementsByClassName("add-to-cart")[0].getAttribute("data-name");

Update:

Use following function:

function myFunction(callingElement) {
        var data_id = $(callingElement).attr('data-id');    
    var x = $(".add-to-cart[data-id *= "+data_id+" ]").attr('data-name');

    alert(x);
    document.getElementById("show-fav").innerHTML = x;
}

and add this to your function argument in onClick.

<button onclick="myFunction(this)" data-id="1">Try it</button>

Hers's the fiddle: https://jsfiddle.net/fs8L366m/

Update 2:

    <script>
        var wishlist = Array(10);
    $(document).ready(function(){
      //wishlist = JSON.parse($.cookie('wishlist') || '{}');
      wishlist = JSON.parse(localStorage.getItem("wishlist") || '{}');
      if(wishlist != null){
      $.each(wishlist, function(index, name){
            $('#wishlist').append($('<li>').val(index).text(name));
        });    
      }
      else
        wishlist = {};
    });


    function myFunction(selectedElement) {
        var data_id = selectedElement.getAttribute("data-id");
        var data_name = $(".add-to-cart[data-id *= "+data_id+" ]").attr('data-name');
      if(!wishlist.hasOwnProperty(data_id)){
        wishlist[data_id] = data_name;
        $('#wishlist').append($('<li>').val(data_id).text(data_name));
        //$.cookie('wishlist', JSON.stringify(wishlist));
        localStorage.setItem("wishlist",JSON.stringify(wishlist));
        //document.cookie = (wishlist);
        console.log($.cookie('wishlist'));
        console.log(wishlist);
      }
      else{
    $('#wishlist li[value *= '+data_id+']').remove();
    delete wishlist[data_id];
    localStorage.setItem("wishlist",JSON.stringify(wishlist));
  }        
        //alert('Element already present');
    }
    </script>
jaysingkar
  • 4,315
  • 1
  • 18
  • 26
  • thanks, yes, I know but I dont know how to add an if statement so that the attribute matching to the ID will only show when the button for that product ID is clicked. – charlie97 Aug 07 '16 at 13:53
  • add all the attributes to button instead of a – jaysingkar Aug 07 '16 at 13:55
  • thanks, this works, however i cant change my html code to that because i have the a tag as a link for products to be added to the shopping cart. so i need a separate button for the wishlist that has the same ID as the product link and only brings the value for that when clicked. – charlie97 Aug 07 '16 at 13:58
  • add the attributes to both then. Is it possible ? – jaysingkar Aug 07 '16 at 13:59
  • @charlie97 can you use jQuery ? – jaysingkar Aug 07 '16 at 14:01
  • yes i can use jquery too but I just dont know how to write the code that would do the below (i would add the class "add-to-fav" to the button too for this): if class name add-to-cart attribute id-name is equal to class name add-to-fav attribute id-name then show attribute data-name in show-fav id element (this is a div that I want to show the results in ) – charlie97 Aug 07 '16 at 14:07
  • Thanks so much for your help, this is exactly what I wanted but I was trying to write it in JS because didint know it all in jQuery. is there a way to store the list instead of them keep changing and make them stay in the HTML? – charlie97 Aug 07 '16 at 14:49
  • I will get you the Javascript function – jaysingkar Aug 07 '16 at 15:10
  • thanks, can you please add the function with it that ables to add each item only once to the list but keep it there without disappearing when clicked on another one? – charlie97 Aug 07 '16 at 15:15
  • sorry I didn't get you. :-( – jaysingkar Aug 07 '16 at 15:21
  • where do you want to store the wishlist items ? – jaysingkar Aug 07 '16 at 15:22
  • sorry im unable to access the chat room. yes basically i want it to be like a wish list where when you add to the list you can add also another item and they will stay in a list and also then store in cookie when refreshed until they get deleted. – charlie97 Aug 07 '16 at 15:34
  • you don't want to send it to server ? – jaysingkar Aug 07 '16 at 15:35
  • no its just to save it to coockie and display the list – charlie97 Aug 07 '16 at 15:42
  • updated first fiddle according to your needs... check it. – jaysingkar Aug 07 '16 at 15:54
  • thank you so much, i put it all in a new html file but its giving me errors in the console: wishlist.html:1 Uncaught SyntaxError: Unexpected token u in JSON at position 0 4wishlist.html:33 Uncaught TypeError: $(...).value is not a function – charlie97 Aug 07 '16 at 16:17
  • I have updated the code. But please note that this will only work in IE as chrome does not support local cookies. http://stackoverflow.com/questions/7925737/jquery-cookie-not-working-on-chrome – jaysingkar Aug 07 '16 at 17:58
  • If this answer solves your problem please consider selecting as a answer – jaysingkar Aug 07 '16 at 17:59
  • thanks, i have added cookies for my product list already and this works on chrome. its just on local storage : function saveCart () { localStorage.setItem("shoppingCart", JSON.stringify(cart)); } im just having difficulties to add it for the wish list – charlie97 Aug 07 '16 at 18:20
  • I'm storing the cookies in this line `$.cookie('wishlist', JSON.stringify(wishlist));` replace it with `localStorage.setItem("wishlist",JSON.stringify(wishlist))`; – jaysingkar Aug 07 '16 at 18:30
  • thank you so much that works, just had a question why there is number 10 in the array? and if I want instead of alert when you click the button again removes the item from list what should I do? – charlie97 Aug 07 '16 at 18:54
1

One approach I could suggest is the following, which removes the inline-event handlers (onclick, etc) from the HTML in favour of unobtrusive JavaScript:

// retrieving the <ul> element that contains the <a>
// and <button> elements:
var priceList = document.getElementById('priceList');

// binding the anonymous function of the
// EventTarget.addEventListener() method to handle
// the 'click' events on the <ul>:
priceList.addEventListener('click', function(e) {
  // 'e' is the event object itself, passed in from
  // addEventListener().

  // caching the variables within the function:
  var list = this,

    // e.target is the element on which the
    // listened-for event was originally fired:
    clicked = e.target,

    // here we create an <li> element:
    li = document.createElement('li'),

    // declaring, but not initialising, a
    // a variable for later use:
    desired;

  // here we check if the originally-clicked element
  // is a <button>, comparing the tagName of the clicked
  // element - converted to lowercase - with the
  // string of 'button':
  if (clicked.tagName.toLowerCase() === 'button') {

    // if a <button> was clicked then we prevent
    // the default action of that <button>:
    e.preventDefault();

    // and look within the <ul> (cached as 'list')
    // using the querySelector() method to find the
    // first instance of an element, if any, matching
    // the supplied selector, the selector here
    // searches for an <a> element, with a 'data-id'
    // attribute with the same attribute-value as held
    // in the clicked element (here we use the
    // HTMLElement.dataset API to retrieve that value):
    desired = list.querySelector('a[data-id="' + clicked.dataset.id + '"]');

    // we set the text-content of the created <li>
    // to be equal to that held within the data-name
    // attribute of the element stored in the
    // 'desired' variable:
    li.textContent = desired.dataset.name;

    // here we simply append the created <li> element
    // to the wishList <ul> element; obviously your
    // own output is likely to be different so adjust
    // to taste as required:
    document.getElementById('wishList').appendChild(li);
  }
});

var priceList = document.getElementById('priceList');

priceList.addEventListener('click', function(e) {
  var list = this,
    clicked = e.target,
    li = document.createElement('li'),
    desired;
  if (clicked.tagName.toLowerCase() === 'button') {
    e.preventDefault();
    desired = list.querySelector('a[data-id="' + clicked.dataset.id + '"]');
    li.textContent = desired.dataset.name;
    document.getElementById('wishList').appendChild(li);
  }
});
li {
  list-style-type: none;
  width: 50%;
  clear: both;
  margin: 0 0 0.5em 0;
  padding: 0 0 0.2em 0;
  border-bottom: 2px solid #aaa;
}
a:link,
a:visited {
  text-decoration: none;
}
a:hover,
a:active,
a:focus {
  text-decoration: underline;
}
a + button {
  float: right;
  padding: 0 1em;
}
<!-- Note the addition of an id attribute ('priceList') to the
     <ul> element, in order to easily target it via JavaScript;
     also the removal of all inline event-handlers in order to
     use unobtrusive JavaScript and minimal repetition -->
<div>
  <ul id="priceList">
    <li><a class="add-to-cart" href="#" data-name="Apple" data-id="1" data-price="1.22">Apple $1.22</a>
      <button data-id="1">Try it</button>
    </li>
    <li><a class="add-to-cart" href="#" data-name="Banana" data-id="2" data-price="1.33">Banana $1.33</a>
      <button data-id="2">Try it</button>
    </li>
    <li><a class="add-to-cart" href="#" data-name="Shoe" data-id="3" data-price="22.33">Shoe $22.33</a>
      <button data-id="3">Try it</button>
    </li>
    <li><a class="add-to-cart" href="#" data-name="Frisbee" data-id="4" data-price="5.22">Frisbee $5.22</a>
      <button data-id="4">Try it</button>
    </li>
  </ul>
</div>

<!-- this element was added purely because you don't clearly
     state where it is that you want the 'names' to be
     'brought' in your question; and this seemed as good an
     idea as any other I could think of to display them -->
<ul id="wishList"></ul>

References:

David Thomas
  • 249,100
  • 51
  • 377
  • 410
  • thanks, instead of keep adding it can it be off and on, for example clicking the button once will add and then click again will remove? – charlie97 Aug 07 '16 at 21:39
  • That's possible, certainly, but it's too late to embark on that here in the UK; I'll try and take some time tomorrow to address that aspect. As it is, though, you should [edit] your question to include your requirements there, that way others trying to help don't have to read all all the comments to all the answers to try and work out what you need. – David Thomas Aug 07 '16 at 23:39
0

Of course, because you give to your variable x the value of the attribute data-name, which is Apple. If you want to obtain Apple $1.22, you should write :

var x = document.getElementsByClassName("add-to-cart")[0].innerHTML;
kevin ternet
  • 4,514
  • 2
  • 19
  • 27
  • thanks, i understand that part but what should the JS code be so that it only shows the data-name value for the data-id button clicked. so for example if the button for banana is clicked it only brings the data-name value banana. – charlie97 Aug 07 '16 at 13:55