JavaScript cant get value of input from my items

Viewed 47

making beginer site and im getting api of crypto Coins and i put them on home page . i put "buy" button with input that i want to fill and buy . i have trying to use getElementsByClassName/ id and its only return the first item. if i log the first item its return value . but if i log all the rest of the items its return "undefined". so i have search a hours on solution and i have found that im using the same "classname" to all items - because of that it return only the first item value . but the problem that i have no idea and i can't find solution.

adding my code . (the map is on homepage)

site image with log coin.js

    import React, { useContext, useState } from 'react'
import './Coin.css';
import { Context } from '../src/context/Context'

const Coin = ({
  name,
  price,
  symbol,
  marketcap,
  volume,
  image,
  priceChange
}) => {
  const { user, dispatch } = useContext(Context);
  // buyCoin function ( buy coin -> checking if user can buy)
  function buyCoin() {
    const coinNumber = document.getElementsByClassName("buyInput").value;
    const coinPrice = { price }.price;
    const wallet = user.wallet;
    if (coinNumber * coinPrice > wallet) {
      alert("you dont have enough money");
      console.log(coinNumber);
      return false;
    } else {
      console.log(coinNumber);
      alert("purchase completed");
      return true;
    };
  }

  return (
    <div className='coin-container'>
      <div className='coin-row'>
        <div className='coin'>
          <img src={image} alt='crypto' />
          <h1>{name}</h1>
          <p className='coin-symbol'>{symbol}</p>
        </div>
        <div className='coin-data'>
          <p className='coin-price'>${price}</p>
          <p className='coin-volume'>${volume.toLocaleString()}</p>
          {priceChange < 0 ? (
            <p className='coin-percent red'>{priceChange.toFixed(2)}%</p>
          ) : (
            <p className='coin-percent green'>{priceChange.toFixed(2)}%</p>
          )}
          <p className='coin-marketcap'>
            ${marketcap.toLocaleString()}
          </p>
           //button to buy the coin
          <button className='buybtn' onClick={buyCoin}>Buy</button>
          <input type="number" className="buyInput"></input>
        </div>
      </div>
    </div>
  );
};
export default Coin;
1 Answers

If you want the value from the input field, I recommend using the state to keep track of the value.

Something like:

const { coinNumber, setCoinNumber } = useState();

And add

<input
  type="number"
  className="buyInput"
  value={coinNumber}
  onChange={setCoinNumber }
></input>

Then you can get your value from coinNumber to use in the buyCoin function.

Related