LoginSignup
0
0

More than 3 years have passed since last update.

【jquery,js】jsの処理をリファクタリングする1 [each,prop] [js02_20210214]

Last updated at Posted at 2021-02-14

処理の概要

重量別の鉄アレイを選択した時、一定の条件(5kg以上、且つ2個以上)をクリアすると送料を無料にする

処理のフロー:

 (1)鉄アレイを選択する(複数可能)
 (2)実行ボタンを押下
 (3)チェックボックスにチェックが入っているかを判断
 (4)チェックされている場合は、重量とカウントを増分させる
 (5)送料を判断する

画面イメージ

画像1

画像2

ソースコード

index.html
<body>
    <input type="checkbox" id="item1" value="1">鉄アレイ:1kg<br>
    <input type="checkbox" id="item2" value="2">鉄アレイ:2kg<br>
    <input type="checkbox" id="item3" value="3">鉄アレイ:3kg<br>
    <input type="checkbox" id="item5" value="5">鉄アレイ:5kg<br>
    <input type="checkbox" id="item10" value="10">鉄アレイ:10kg<br><br>
    <input type="button" id="execbutton" value="実行" >
    <br>
    <div id="output"></div>
</body>

リファクタリングする前

main.js

$(function() {
    $("#execbutton").click(function(){
        var weight = 0;
        var count = 0;

        if($("#item1").prop("checked")){
            weight += $("#item1").val() * 1;
            count += 1;
        }

        if($("#item2").prop("checked")){
            weight += $("#item2").val() * 1;
            count += 1;
        }

        if($("#item3").prop("checked")){
            weight += $("#item3").val() * 1;
            count += 1;
        }

        if($("#item5").prop("checked")){
            weight += $("#item5").val() * 1;
            count += 1;
        }

        if($("#item10").prop("checked")){
            weight += $("#item10").val() * 1;
            count += 1;
        }

        if(weight >= 5 ){
            if(count >= 2){
                $("#output").text("送料は無料です。");
            } else {
                var lobjValue = weight * 110 ;
                $("#output").text("送料は" + lobjValue + "円です。");
            }
        } else {
            $("#output").text("送料は無料です。");
        }
    })
});

リファクタリング後

main.js

$(function() {
    $("#execbutton").click(function(){
        var weight = 0;
        var count = 0;

        $("input[type='checkbox']").each(function(){
            if($(this).prop("checked")){
                count += 1;
                weight += $(this).val() * 1
            }
        });

        if(weight >= 5 && count >=2 ){
            $("#output").text("送料は無料です。");
        } else {
            var lobjValue = weight * 110 ;
            $("#output").text("送料は" + lobjValue + "円です。");
        }
    })
});

ポイント

html:
(1)選択したチェックボックスには該当する値を設定する(value)
js:
(1)propで属性を取得する
(2)「$("input[type='checkbox']").each」でページ全体のチェックボックスについて、配列を取得する。これをeach文で、無名関数に渡す。
(3)ここでのthisはeachで取得した要素を指す
(4)画面オブジェクトから入力される値は基本的に文字列

参考資料

JavaScript(仕事の現場でサッと使える!デザイン教科書) p120

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