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.

選択済みのラジオボタンを再度押して解除できるようにする

Posted at

選択済みのラジオボタンに対して、チェックボックスのように再度押すことで解除できるようにするJavaScriptのサンプル。
複数グループにも対応。

動作デモ

test.html
<!DOCTYPE html>
<html lang='ja'>
<head>
<meta charset='utf-8'>
<title>ラジオボタン 解除対応サンプル</title>
</head>
<body>
groupA:
<label><input type='radio' name='groupA' value='1'>1</label>
<label><input type='radio' name='groupA' value='2'>2</label>
<label><input type='radio' name='groupA' value='3'>3</label>
<br>

groupB:
<label><input type='radio' name='groupB' value='1'>1</label>
<label><input type='radio' name='groupB' value='2'>2</label>
<label><input type='radio' name='groupB' value='3'>3</label>
<br>

groupC:
<label><input type='radio' name='groupC' value='1'>1</label>
<label><input type='radio' name='groupC' value='2'>2</label>
<label><input type='radio' name='groupC' value='3'>3</label>
<br>

<script>
'use strict';
{
    window.addEventListener('DOMContentLoaded', function() {
        const
            radioElements = document.querySelectorAll('input[type=radio]'),
            state = {};

        for(let i = 0; i < radioElements.length; ++i) {
            radioElements[i].addEventListener('click', function() {
                if(state[this.name] === this.value) state[this.name] = this.checked = false;
                else state[this.name] = this.value;
            });
        }
    });
}
</script>
</body>
</html>
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?