Dataset Understanding

<?php  ?>
<html lang="en" dir="ltr">
	<head>
		<meta charset="utf-8">
		<title>Shopping Cart Course</title>
		<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
		<style>
		.item {
			border: 1px solid black;
			padding: 20px;
			width: 200px;
			float: left;
		}
		</style>
	</head>
	<body>

		<div class="item">
        <h3>iPhone</h3><img src="http://placehold.it/350x150" class="img-fluid">
        <div>Product information description why its the best product ever blah blah <a href="#" class="productItem" data-name="iPhone" data-s="black" data-price="50000" data-id="1">Add to Cart</a> </div>
    </div>
    <div class="item">
        <h3>iPad</h3><img src="http://placehold.it/350x150" class="img-fluid">
        <div>Product information description why its the best product ever blah blah <a href="#" class="productItem" data-name="iPad" data-s="white" data-price="30000" data-id="2">Add to Cart</a> </div>
    </div>
    <div class="item">
        <h3>Cable 3</h3><img src="http://placehold.it/350x150" class="img-fluid">
        <div>Product information description why its the best product ever blah blah <a href="#" class="productItem" data-name="Cable" data-s="3" data-price="1200" data-id="3">Add to Cart</a> </div>
    </div>
    <div class="item">
        <h3>SD Card 32GB</h3><img src="http://placehold.it/350x150" class="img-fluid">
        <div>Product information description why its the best product ever blah blah <a href="#" class="productItem" data-name="SD Card" data-s="32GB" data-price="3000" data-id="4">Add to Cart</a> </div>
    </div>
    <div class="item">
        <h3>SD Card 16GB</h3><img src="http://placehold.it/350x150" class="img-fluid">
        <div>Product information description why its the best product ever blah blah <a href="#" class="productItem" data-name="SD Card" data-s="16GB" data-price="2000" data-id="5">Add to Cart</a> </div>
    </div>
    <div class="item">
        <h3>SD Card 4GB</h3><img src="http://placehold.it/350x150" class="img-fluid">
        <div>Product information description why its the best product ever blah blah <a href="#" class="productItem" data-name="SD Card" data-s="4GB" data-price="1000" data-id="6">Add to Cart</a> </div>
    </div>
    <div id="output"> </div>



		<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
		<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js">
		</script>
		<script>
		$(document).ready(function(){
			var shopcart = [];
			$(".productitem").click(function(e){
				e.preventDefault();
				var iteminfo = $(this.dataset)[0];
				iteminfo.qty = 1;
				shopcart.push(iteminfo);
				console.log(shopcart);
			})
		})

		</script>
	</body>
</html>

I am unable to fully understand this part →

var iteminfo = $(this.dataset)[0];

what is it actually picking from the HTML?

Live Code Here

Hi there codeispoetry,

I am not a javascript expert, but I thought one would
access the dataset object something like l this…

<!DOCTYPE HTML>
<html lang="en">
<head>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width,height=device-height,initial-scale=1">

</head>
<body> 
 <ul>
  <li><a href="#" class="productItem" data-name="iPhone" data-s="black" data-price="50000" data-id="1">Add to Cart</a></li>
  <li><a href="#" class="productItem" data-name="iPad" data-s="white" data-price="30000" data-id="2">Add to Cart</a></li>
  <li><a href="#" class="productItem" data-name="Cable" data-s="3" data-price="1200" data-id="3">Add to Cart</a></li>
  <li><a href="#" class="productItem" data-name="SD Card" data-s="32GB" data-price="3000" data-id="4">Add to Cart</a></li>
  <li><a href="#" class="productItem" data-name="SD Card" data-s="16GB" data-price="2000" data-id="5">Add to Cart</a></li>
  <li><a href="#" class="productItem" data-name="SD Card" data-s="4GB" data-price="1000" data-id="6">Add to Cart</a></li>
 </ul>

<script>
(function( d ) {
   'use strict';
   var c, a = d.querySelectorAll('.productItem');
   for ( c = 0; c < a.length; c ++ ) {
         a[ c ].addEventListener( 'click', doStuff(c), false );
      }

function doStuff(c) {
   a[ c ].onclick=function( e ) {
        e.preventDefault();
        console.log( this.dataset.s ); /* or -  dataset.name , dataset.price, dataset.id */
     };
   }    
}( document ));
</script>

</body>
</html>

coothead

1 Like

Hey there sir,

Actually I am trying to build a e-commerce store for learning by seeing a video series on udemy.com, but the author rarely replies so I was seeking help here.

Hi there codeispoetry,

actually, I am just trying to point out that I believe that you require…

  1. dataset.name - rather than - dataset[0]
  2. dataset.s - rather than - dataset[1]
  3. dataset.price - rather than - dataset[2]
  4. dataset.id - rather than - dataset[3]

coothead

1 Like

Ok quiet possible author is not Pro in his approach. I will try and test them.

Sir, would it be possible if you can comment on the actual question.

I thought the actual question was…

…what is it actually picking from the HTML?

…and by it, that you were referring to dataset[0]. :winky:

So, to the best of my knowledge dataset[0] should be
dataset.name and refers to the data-name attribute in
the HTML code.

coothead

1 Like

Ok. so the 1st one in the HTML DIV.

Thats what you was trying to tell that better way is this→

What I was trying to to tell you was that, to the best of my knowledge,

…dataset[0] dataset[1] dataset[2] dataset[3] is not valid code. :rofl:

coothead

2 Likes

Hi there codeispoetry,

here is the source of my assertion…

https://developer.mozilla.org/en-US/docs/Web/API/HTMLOrForeignElement/dataset

coothead

1 Like

Hey there @coothead

You must be right sir, but the author is consistently using the same thing. This is his final code:

<script>
        var shopcart = [];
        $(document).ready(function () {
            outputCart();
            $(".productItem").click(function (e) {
                e.preventDefault();
                var iteminfo = $(this.dataset)[0];
                iteminfo.qty = 1;
                var itemincart = false;
                $.each(shopcart, function (index, value) {
                    //console.log(index + '  ' + value.id);
                    if (value.id == iteminfo.id) {
                        value.qty = parseInt(value.qty) + parseInt(iteminfo.qty);
                        itemincart = true;
                    }
                })
                if (!itemincart) {
                    shopcart.push(iteminfo);
                }
                sessionStorage["sca"] = JSON.stringify(shopcart);
                outputCart();
                ///
            })

            function outputCart() {
                if (sessionStorage["sca"] != null) {
                    shopcart = JSON.parse(sessionStorage["sca"].toString());
                    console.log(sessionStorage["sca"]);
                }
                var holderHTML = '';
                var total = 0;
                $.each(shopcart, function (index, value) {
                    console.log(value);
                    var stotal = value.qty * value.price;
                    total += stotal;
                    holderHTML += '<div>Item ' + value.name + '(' + value.s + ') Qty ' + value.qty + ' Price ' + formatMoney(value.price) + ' ID(' + value.id + ') subtotal = ' + formatMoney(stotal) + '</div>';
                })
                holderHTML += '<div>' + formatMoney(total) + '</div>';
                $('#output').html(holderHTML);
            }

            function formatMoney(n) {
                return '$' + (n / 100).toFixed(2);
            }
        })
    </script>

In that case it must be one of jQuery’s work-arounds. :eek:

Personally, I only use the Vanilla flavour. :winky:

coothead

1 Like

OK sir.

This reads as “Select the nodes defined by the selector contained in this.dataset; then select the first node returned by this selection.”
By default, this.dataset should contain an array (technically i think it’s an object, actually) of all elements of the data-* set of attributes of the element.
Based on this, I assume there is more than 1 element with the same data- attributes, otherwise the selector is rather moot, and could be said to be this.

1 Like

This is the HTML →

<div class="item">
        <h3>iPhone</h3><img src="http://placehold.it/350x150" class="img-fluid">
        <div>Product information description why its the best product ever blah blah <a href="#" class="productItem" data-name="iPhone" data-s="black" data-price="50000" data-id="1">Add to Cart</a> </div>
    </div>
    <div class="item">
        <h3>iPad</h3><img src="http://placehold.it/350x150" class="img-fluid">
        <div>Product information description why its the best product ever blah blah <a href="#" class="productItem" data-name="iPad" data-s="white" data-price="30000" data-id="2">Add to Cart</a> </div>
    </div>
    <div class="item">
        <h3>Cable 3</h3><img src="http://placehold.it/350x150" class="img-fluid">
        <div>Product information description why its the best product ever blah blah <a href="#" class="productItem" data-name="Cable" data-s="3" data-price="1200" data-id="3">Add to Cart</a> </div>
    </div>
    <div class="item">
        <h3>SD Card 32GB</h3><img src="http://placehold.it/350x150" class="img-fluid">
        <div>Product information description why its the best product ever blah blah <a href="#" class="productItem" data-name="SD Card" data-s="32GB" data-price="3000" data-id="4">Add to Cart</a> </div>
    </div>
    <div class="item">
        <h3>SD Card 16GB</h3><img src="http://placehold.it/350x150" class="img-fluid">
        <div>Product information description why its the best product ever blah blah <a href="#" class="productItem" data-name="SD Card" data-s="16GB" data-price="2000" data-id="5">Add to Cart</a> </div>
    </div>
    <div class="item">
        <h3>SD Card 4GB</h3><img src="http://placehold.it/350x150" class="img-fluid">
        <div>Product information description why its the best product ever blah blah <a href="#" class="productItem" data-name="SD Card" data-s="4GB" data-price="1000" data-id="6">Add to Cart</a> </div>
    </div>
    <div id="output"> </div>

I have put the code live here.

Yeah… I can’t say I understand the idea behind that, then.

Because the only element in that HTML that has a matching set of data attributes is the link that you’re clicking on, $(this.dataset)[0] will find that link and give it a new attribute.

Seems… rather redundant, given you already know what this is…

1 Like

I am following a Video series and learn as much as I can in first watching. simultaneously coding so that I can learn something.

Hopefully this will help to resolve misunderstandings.

When I set a breakpoint on that line, I find that the this keyword refers to one of the “Add to Cart” links that was clicked on.

<a href="#" class="productItem" data-name="Cable"
   data-s="3" data-price="1200" data-id="3">Add to Cart</a>

The dataset property gives you easy access to the data keywords on that object, which include data-name, data-s, data-price, and data-id.

That gives you what looks like an object (and is really a DOMStringMap) with the following information:

{
    name: "Cable",
    s: "3",
    price: "1200",
    id: "3"
}

That dataset property also gives you read/write access to the HTML data attributes.

The next part, wrapping this.dataset in a jQuery object and getting the zeroth item which gives $(this.dataset)[0], just seems a wasteful confusion, for you still end up with the same dataset object.

2 Likes

I had assumed that the HTML would have contained some sort of placeholder <input> tags or something for submission via form. Instead it looks (from post 10) that the author eventually abandons this approach and instead stores the items in a standard array-into-json style.

I still see no benefit to the usage of the node selector in the final code version.

I agree.

Instead of this code:

var iteminfo = $(this.dataset)[0];

Exactly the same thing is achieved with less confusion, using this:

var iteminfo = this.dataset;
1 Like

This was the author’s position while he was educating in video series

(zip file deleted - potential security risk)