0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

選択式クイズの実装 (html) (js)

Last updated at Posted at 2021-09-22

実装内容

選択式問題の実装と、正解or不正解を判定する回答ボタンを実装します。
その他の仕様は以下となります。
・問題にはラジオボタン、チェックボックス(複数回答)どちらも使用
・全て回答で、回答ボタンを活性化
・回答ボタン押下で回答結果を表示

See the Pen 選択式クイズの実装 by amo_sh (@amo_sh) on CodePen.

html
<div>
 <p>Q1</p>
 <input type="radio" name="q1" id="q101"><label for="q101">答え(正解)</label>
 <input type="radio" name="q1" id="q102"><label for="q102">答え</label>
 <input type="radio" name="q1" id="q103"><label for="q103">答え</label>
</div>
<div>
 <p>Q2(複数選択)</p>
 <input type="checkbox" name="q2" id="q201"><label for="q201">答え(正解)</label>
 <input type="checkbox" name="q2" id="q202"><label for="q202">答え(正解)</label>
 <input type="checkbox" name="q2" id="q203"><label for="q203">答え</label>
</div>
<button class="btn">答え合わせをする</button>
<p class="answer">回答:</p>
js
$(function(){
     $('input').change(function() {
        //チェックされた項目のnameを取得
        const checked = $('input:checked').map(function(){
            return $(this).attr('name');
          }).get();
        //全て回答されたら回答ボタンを活性化
        if (/^q1.*q2/.test(checked)) {
            $('.btn').addClass('on');
        } else {
             $('.btn').removeClass('on');
        }
    });
    $('.btn').click(function() {
        //チェックされた項目のidを取得
        const answer = $('input:checked').map(function(){
            return $(this).attr("id");
          }).get();
        //答え合わせ
        if ($(this).hasClass('on')) {
            if (answer =='q101,q201,q202') {  
              $('.answer').text('回答:正解');
            } else {
              $('.answer').text('回答:不正解');
            }
        } else {
            return false;
        }
    });
  });

すべて回答されているかチェック

.map()で、「チェックされているinputのnameを取得」します。
.test()で、取得したnameを正規表現で比較します。
q1とq2があればtrueを返します

js
const checked = $('input:checked').map(function(){
            return $(this).attr('name');
          }).get();
//取得例:q1,q2

/^q1.*q2/.test(checked)
//checkedの値が q1 の場合 = false
//checkedの値が q1,q2 の場合 = true
//checkedの値が q1,q2 ,q2の場合 = true

答え合わせ

.map()で、「チェックされているinputのidを取得」します。
回答があっているか比較します。

js
const answer = $('input:checked').map(function(){
            return $(this).attr('id');
          }).get();
//Q1の答え(q101)をチェックした場合 = q101
//Q1の答え(q101)と、Q2の答え(q201)、をチェックした場合 = q101,q201

answer =='q101,q201,q202'
//checkedの値が q101,q201 の場合 = false
//checkedの値が q101,q201,q202 の場合 = true

最後に

私自身まだまだ初心者のため、非効率な組み方があるかもしれません。
ご指導ご鞭撻のほどお願いいたします。

0
0
1

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?