JavaScriptによる製品計算機
このセクションでは、製品計算機を実装します。 これは、ウェブサイトのユーザーが購入品を入力する テーブルになります。
購入品はフォームを通じて入力されるようにします。さらに、 各製品には削除用のリンクを設けます。また、製品の 名前、価格、数量を編集できる機能も作成します。 この編集は、テーブルのセルをダブルクリックすることで 行われるようにしましょう。
テーブルの下には、製品の合計金額を表示します。 この合計金額は、製品の削除や編集時に再計算される ようにしましょう。
完成形の見本は以下の通りです:
タスクを解く際に使用できるマークアップは 以下の通りです:
<div id="parent">
<div id="form">
<input id="name" placeholder="名称">
<input id="price" placeholder="価格">
<input id="amount" placeholder="数量">
<input id="add" type="button" value="追加">
</div>
<h2>製品テーブル:</h2>
<table id="table">
<tr>
<th>名称</th>
<th>価格</th>
<th>数量</th>
<th>小計</th>
<th>削除</th>
</tr>
</table>
<div id="result">
合計金額: <span id="total">0</span>
</div>
</div>
* {
box-sizing: border-box;
}
#parent {
margin: 0 auto;
width: 500px;
}
#form {
display: flex;
margin-bottom: 15px;
}
#form input {
padding: 8px;
width: 24%;
margin: 0 0.5% 10px 0.5%;
}
h2 {
margin-top: 0;
margin-bottom: 7px;
}
#table {
width: 100%;
margin-bottom: 10px;
}
#table td, #table th {
padding: 8px;
text-align: center;
border: 1px solid black;
}
#table td.remove {
color: blue;
cursor: pointer;
text-decoration: underline;
}
#table td.remove:hover {
text-decoration: none;
}
#result {
text-align: right;
margin-right: 10px;
}
では、必要なすべてのタグへの参照を変数に 取得しましょう:
let name = document.querySelector('#name');
let price = document.querySelector('#price');
let amount = document.querySelector('#amount');
let add = document.querySelector('#add');
let table = document.querySelector('#table');
let total = document.querySelector('#total');
私が提示したコードのテンプレートを 自身の環境にコピーしてください。