The original tutorial calls these “period buttons”; in HTML they are radio buttons. Clicking a radio button can run JavaScript, update the URL, or submit a form. The original male/female query-string demo and Submit control are preserved.
Demo of the onclick event of radio button
const selected = document.querySelector('input[name="type"]:checked');
if (selected) {
console.log(selected.value);
}
This avoids looping over every radio control just to find the checked item.
function reloadWithType(value) {
const url = new URL(window.location.href);
url.searchParams.set('type', value);
window.location.href = url.toString();
}
If selecting a radio option should immediately submit the form, listen for change or click and call requestSubmit(). Keep an explicit Submit button when users may prefer to review before submission.
radio.addEventListener('change', () => {
form.requestSubmit();
});
<form name="form1" method="post" action="" id="typeForm">
<input type="radio" name="type" value="male"> Male
<input type="radio" name="type" value="female"> Female
<input type="submit" value="Submit">
</form>
<script>
const form = document.getElementById('typeForm');
form.querySelectorAll('input[name="type"]').forEach((radio) => {
radio.addEventListener('click', () => {
const url = new URL(window.location.href);
url.searchParams.set('type', radio.value);
window.location.href = url.toString();
});
});
</script>
Event Handling onMouseOver and onMouseOut
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.
| alex | 03-03-2012 |
| Good article, helped a lot. Thanks | |