Material Box

Material Box

WEB Design & Material Images

JavaScript - Radio button change event

JavaScript

A simple code example introducing how to implement a radio button change event using addEventListener() in JavaScript.


The HTML has radio buttons with class "radio-btn" to detect value changes.

<div class="item-container">
	<p id="output">checked : A</p>
	<div class="radio-btns">
		<p><input type="radio" name="type" class="radio-btn" value="A" checked>A</p>
		<p><input type="radio" name="type" class="radio-btn" value="B">B</p>
		<p><input type="radio" name="type" class="radio-btn" value="C">C</p>
	</div>
</div>

The target radio buttons are queried with querySelectorAll() and addEventListener() is used on each button to implement a "change" event to detect value changes.

The code example displays the changed value in the output area when radio buttons change.

// Get all target radio buttons
let radio_btns = document.querySelectorAll('.radio-btn');

// Add change event to each button
for (let target of radio_btns) {
	target.addEventListener(`change`, () => {
		// Display result in output area
		document.querySelector(`#output`).innerHTML = `checked : ${target.value}`;
	});
}

JavaScript - Radio button change event

TitleJavaScript - Radio button change event

CategoryJavaScript

Created

Update

AuthorYousuke.U