Problem with identification / Function

Asked

Viewed 31 times

-1

I have 2 items for sale and, under such, we have buttons that lead to Function comprar(). Ssegue the code:

Item 1:

<h1 Bola </h1>
<p 5 reais /q>
<input type="button" value="Comprar" onclick='comprar()'>

Item 2:

<h1 Chiclete </h1>
<p 2 reais /q>
<input type="button" value="Comprar" onclick='comprar()'>

Which parameter/ argument I need to use in Function comprar() to identify which item I refer to?

  • An example: https://repl.it/@Dadinel/Affectionateharsharguments, good studies! :)

1 answer

0

You would need to pass the key to the item. Something is mounting it on the screen right? Whether it’s a PHP or even an Angularjs, it doesn’t matter, when you build this screen, you need to bring a value that references the item. The buy function will always be called, so within the function you need to pass a variable warning which will be the item, it can be the id of this item ( or even the name of the div, since each div needs to have its unique value).

For example:

<legend>Item 1:</legend>

<h1> Bola </h1>
<p> 5 reais </p>
<input type="button" value="Comprar" onclick="comprar('1')">

<legend>Item 2:</legend>

<h1> Chiclete </h1>
<p> 2 reais </p>
<input type="button" value="Comprar" onclick="comprar('2')">

function comprar(item){
 //'item' corresponde ao valor passado na chamada da função, no exemplo, 1 ou 2
}

Note: There are better ways to do this through Jquery, for example.

  • After that I would have to do?: if (item == 1) console.log('ball'') If so I would always have to add an ID manually, imagine a store with 500 items.

  • Friend, in a store of 500 items, each item has its individual id. You only have to add manually if you are creating the items individually. Which BD are these items saved? Items must have a primary key. Use this key to reference them on the purchase page. The point is that you do not set up a store only with JS, and what you posted was only related to JS. How the data comes to your page? Ajax?.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.