Jiang Lan Jiang Lan - 7 months ago 17
Javascript Question

How to access the corresponding object's value according to the click in javascipt

Here is the sample in jsFiddle

Fiddle

I post the code here too,

html:

<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 4 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 the 2, when the fruit is not match up, do
append
.

I know I ask 2 extra questions according to the title, but since they are stick together, I will ask by one time.

Answer

I would simplify this problem slightly by adding a quantity to your Produit object and adding an ID to each link. You can use $(this).text() to access the text value of each link, but the ID will be more reliable and makes for simpler code. I'm not sure if you're concerned with the order the products show up in the list within your div... The solution below just iterates through your array of products and displays the quantities of all that are greater than 0.

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

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

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

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

$('a').click(function(){
  var id = $(this).attr("id").replace("produit_","");
  produit[id].qty++;
  var div = '';
  for(var i = 0; i<produit.length; i++){
    if(produit[i].qty>0)
      div += produit[i].nom + ' x ' + produit[i].qty + '<br/>'
  }
  $('div').html(div);
});
Comments