charlie97
charlie97

Reputation: 51

Get attribute value for each specific element by matching it to another attribute value

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

Upvotes: 1

Views: 1985

Answers (3)

jaysingkar
jaysingkar

Reputation: 4435

        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>

Upvotes: 1

David Thomas
David Thomas

Reputation: 253338

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:

Upvotes: 1

kevin ternet
kevin ternet

Reputation: 4612

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;

Upvotes: 0

Related Questions