LoginSignup
1
1

More than 3 years have passed since last update.

【Railsアプリ】販売手数料をJavaScriptで計算しようとしたら出てくる「NaN」を解決できたので、備忘録として残しておきます。

Posted at

ミス内容

スクリーンショット 2020-12-27 19.59.06.png
入力された金額の販売手数料(10%)を、JavaScriptを使って計算しようという実装を行っていた時に突如現れた「NaN」。
最初のコードは以下の通り。

function calc (){
  // id="item-priceの要素を取得。
  const itemPrice = document.getElementById("item-price");
  // 値が入力された時にイベントを発火。
  itemPrice.addEventListener('input', function(){
    const Tax = 0.1;
    const tax_fee = itemPrice * Tax;
    const profit = itemPrice - tax_fee;
    const taxArea = document.getElementById("add-tax-price");
    const profitArea = document.getElementById("profit");
    taxArea.innerHTML = tax_fee;
    profitArea.innerHTML = profit;
  })
}

window.addEventListener('load', calc)

原因

NaN = Not-a-Number(数字ではない)
計算しようとしている値が数字になっていないよ、と伝えているようです。

上記のコードだと、
getElementByIdで取得した「要素」と、
Tax=0.1という「数値」をかけ算しようとしている。

つまり、要素の値を取得した上で、
「数値」と「数値」をかけ算しなければならないのです><

解決法

itemPrice.valueで、要素の「値(=数値)」を取得しましょう。

function calc (){
  // id="item-priceの要素を取得。
  const itemPrice = document.getElementById("item-price");
  // 値が入力された時にイベントを発火。
  itemPrice.addEventListener('input', function(){
    // 下記を追記して、要素の値を取得。
    const itemPriceValue = itemPrice.value
    const Tax = 0.1;
    const tax_fee = itemPriceValue * Tax;
    const profit = itemPriceValue - tax_fee;
    const taxArea = document.getElementById("add-tax-price");
    const profitArea = document.getElementById("profit");
    taxArea.innerHTML = tax_fee;
    profitArea.innerHTML = profit;
  })
}

window.addEventListener('load', calc)

これで「NaN」が消え、計算機能を実装することができました!

スクリーンショット 2020-12-27 20.21.42.png

おわりに

最初、「NaN」ってナンだよ、、、と思いましたが、要素と数値はかけ算できないという初歩的なミスでした。

このミスを解説してくれたメンターさんが仰った『JavaScriptはHTMLをほじくりまわす言語だ』の一言がなぜか胸に刺さりました^^

プログラミングは面白い。もっと使いこなしたいです。

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1