Jiang Lan Jiang Lan - 5 months ago 11
Javascript Question

How to access a corresponding object's value according to the click

Here is the sample in JSFiddle

<a href="#"></a>
<a href="#"></a>
<a href="#"></a>
<a href="#"></a>
<div></div>


JavaScript:

function Produit(nom, prix){
this.nom = nom;
this.prix = prix;
};

var apple = new Produit("apple", 0.30);
var banana = new Produit("banana", 0.03);
var pear = new Produit("pear", 0.35);
var kiwi = new Produit("kiwi", 0.40);

var produit = [apple,banana,pear,kiwi];

for(var i = 0; i < produit.length; i++){
$('a').eq(i).html(produit[i].nom + '<br/>');
};

$('a').click(function(){
var quantity = 0;
quantity++;
$('div').append(produit[0].nom + ' x ' + quantity + '<br/>');
});


So in the browser, we have four fruits. What I want is:


  1. when I click a fruit, it will shows it's name and the quantity,

  2. if I click on apple 2 times, it will shows 'apple x 2',

  3. then if I click on kiwi, it will shows 'kiwi x 1' under 'apple x 2'

    As I don't know how to do that, in my code, I just put the 0 index of the table, to show you what it looks like.



What I know is:

- For 1, I need a
this
to replace the
0
in the
produit[ ]
, but I don't know how to apply
this
.

- For 2, I need a counter and an
if/else
, to compare that, once a fruit is clicked, the second click on it will increase the quantity, not append a new
<div>
.

- For 3, it will be in the
else
with #2, when the fruit is not match up, do
append
.

Answer

You'll need to write the results to an array, then rewrite the div contents. Use .html() instead of .append()

function Produit(nom, prix){
    this.nom = nom;
    this.prix = prix;
};

var apple = new Produit("apple", 0.30);
var banana = new Produit("banana", 0.03);
var pear = new Produit("pear", 0.35);
var kiwi = new Produit("kiwi", 0.40);

var produit = [apple,banana,pear,kiwi];

for(var i = 0; i < produit.length; i++){
    $('a').eq(i).html(produit[i].nom + '<br/>');
};

a = {};
a.nameArray = [];
a.valueArray = [];
myString = "";

$('a').click(function(){
  var itemClicked = this.innerHTML.replace("<br>","");

  //if the nameArray does NOT contain the product, add it, and set value to 1.  If it does contain the product, increment value by 1.
  if(a.nameArray.indexOf(itemClicked)==-1){
    a.nameArray.push(itemClicked);
    a.valueArray.push(1);
  } else {
    a.valueArray[a.nameArray.indexOf(itemClicked)] += 1;
  }

  //write the string based on contents of arrays
  myString = "";
  for(var i=0; i<a.nameArray.length;i++){
    myString += a.nameArray[i] + " x " + a.valueArray[i] + "<br/>";
  }

  //Rewrite the contents of the html div.
    $('div').html(myString);
});
<a href="#"></a>
<a href="#"></a>
<a href="#"></a>
<a href="#"></a>
<div></div>

https://jsfiddle.net/s02ch9mt/1/