0
0

# フリマアプリで販売手数料や販売利益を表示させたい(JavaScript)

Posted at

はじめに

プログラミング初心者です。
現在フリマアプリを作成中、終盤です。
今回アプリが完成し最終チェックをしていたところ、エラーが一つ飛び出てきたので記録します。

JavaScriptで販売手数料や販売利益を表示させたい

今回のエラーとして、商品を出品する際に金額を入力すると販売手数料と販売利益が自動で出力される機能を実装したが、なんらかのエラーで保存がされなかった場合に前述の二つの項目が出力されなくなってしまうというものでした。
端的にコードを貼り付けて記録しちゃいます。

Before

window.addEventListener('turbo:load', () => {

  const priceInput = document.getElementById("item-price");
  priceInput.addEventListener("input", () => {
    const inputValue = priceInput.value;

    const addTaxDom = Math.floor(inputValue * 0.1);
    const addTaxDomElement = document.getElementById("add-tax-price");
    addTaxDomElement.textContent = addTaxDom;

    const salesProfit = Math.floor(inputValue * 0.9);
    const salesProfitElement = document.getElementById("profit");
    salesProfitElement.textContent = salesProfit;
  });
};

After

const price = () => {

  const priceInput = document.getElementById("item-price");
  priceInput.addEventListener("input", () => {
    const inputValue = priceInput.value;

    const addTaxDom = Math.floor(inputValue * 0.1);
    const addTaxDomElement = document.getElementById("add-tax-price");
    addTaxDomElement.textContent = addTaxDom;

    const salesProfit = Math.floor(inputValue * 0.9);
    const salesProfitElement = document.getElementById("profit");
    salesProfitElement.textContent = salesProfit;
  });
};

window.addEventListener("turbo:load", price);
window.addEventListener("turbo:render", price);

解説

訂正したのは以下の二つです。
1、コードを関数化し、最後の行で呼び出している。
2、ページがrenderされたときにも表示されるようにしている。(今回のエラー原因)

window.addEventListener("turbo:render", price);

最後のこの行で、なんらかの不具合でエラーになり再度入力ることになった時、また販売手数料と販売利益が出力されるようになります。

今回は以上です。

0
0
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
0
0