LoginSignup
1
1

More than 3 years have passed since last update.

jQuery checkboxの流れ

Posted at

今回、チェックをつけた項目をアラートに表示させる実装をしました。
備忘録として、コードの流れを記録します。

590baee4c13d52510a51f710c028910d.png

コード全体はこう

$(function() {
  $('form').on('submit', function(e) {
    let output = ''; 
    let checkboxes = $(this).find('input[type="checkbox"]');
    checkboxes.each(function(i, checkbox) {
      checkbox = $(checkboxes[i]);
      if (checkbox.prop('checked')) {
        output += checkbox.attr('value') + '\n';
      }
    });
    e.preventDefault();
    alert('あなたが選んだ果物:\n' + output);
  });
});

①まずリロードした際に実行されるよう関数で囲む

$(function() {
});

②formタグのsubmitに実装する

$(function() {
 $('form').on('submit' function(){
 });
});

③preventDefault()の引数にeを指定し、デフォルトで設定されているイベントをキャンセルする。

$(function() {
 $('form').on('submit' function(e){
  e.preventDefault();
 });
});

④最終的に表示したい値と、空の変数を用意

$(function() {
 $('form').on('submit' function(e){
  let output = '';
  e.preventDefault();
  alert('あなたが選んだ果物:\n' + output);
 });
});

⑤イベントで取得する値をinput要素のcheckboxに指定し、変数checkboxesに代入

$(function() {
 $('form').on('submit' function(e){
  let output = '';
  let checkboxes = $(this).find('input[type="checkbox"]');
  e.preventDefault();
  alert('あなたが選んだ果物:\n' + output);
 });
});

⑥チェックボックスの値をバラして取得するために、functionの引数にi(index)とcheckboxを指定。

$(function() {
 $('form').on('submit' function(e){
  let output = '';
  let checkboxes = $(this).find('input[type="checkbox"]');
 checkboxes.each(function(i, checkbox) {});
  e.preventDefault();
  alert('あなたが選んだ果物:\n' + output);
 });
});

⑦if文でoutputに洗濯したvalueを代入して完成

$(function() {
  $('form').on('submit', function(e) {
    let output = ''; 
    let checkboxes = $(this).find('input[type="checkbox"]');
    checkboxes.each(function(i, checkbox) {
      checkbox = $(checkboxes[i]);
      if (checkbox.prop('checked')) {
        output += checkbox.attr('value') + '\n';
      }
    });
    e.preventDefault();
    alert('あなたが選んだ果物:\n' + output);
  });
});

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