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 1 year has passed since last update.

【JavaScript】【Jquery】チェックボックスで片方チェックしたら片方外す

Last updated at Posted at 2023-07-20

html inputでtypeがcheckboxのセレクタが対象

<div>
  <div>
    <label><input type="checkbox" id=1 value=2>チェック1</label>
    <label><input type="checkbox" id=2 value=1>チェック2</label>
  </div>
  <div>
    <label><input type="checkbox" id=3 value=1>チェック1</label>
    <label><input type="checkbox" id=4 value=1>チェック2</label>
  </div>
</div>
<p></p>

js

$('label input[type="checkbox"]').change(function() {
  //両方チェックを外す
  $(this).closest('div').find('label input[type="checkbox"]').prop('checked', false);
  //押したチェックボックスにチェックする
  $(this).prop('checked', true);
   //チェック数をカウント
  $('p').text($('input:checked').length);
   //チェックされてるvalueの合計       
  let sum = $('input:checked').get().reduce((sizai, gokei) => + gokei.value + sizai, 0);
  console.log(sum);
 //チェックされてるidの配列を作成    
  let ids = $('input:checked').map((_,e) => $(e).attr('id')).get();
   console.log(ids);
})

実行環境
https://jsfiddle.net/nishikawa_naonori/of0xnzut/3/

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?