I wanted to retrieve value from a bootstrapped button group. I have disable the name attribute on the buttons other than the one which is set active in my attempt to do so. But this approach doesn't work. Can't someone please suggest me a convenient way to do it through the toggleActiveInBtnGroup() function, as many other elements in my form utilize this function.
const toggleActiveInBtnGroup = (className, elements, selectedId) => {
for (let i = 0; i < elements.length; ++i) {
if (`${className}-${i}` != selectedId) {
elements[i].classList.remove("active");
elements[i].removeAttribute("name");
} else {
elements[i].className += " active";
elements[i].setAttribute("name", className);
}
console.log(elements[i]);
}
}
const onGenderChange = (event) => {
const className = "gender";
const elements = document.getElementsByClassName(className);
const selectedId = event.target.id;
toggleActiveInBtnGroup(className, elements, selectedId);
}
function onFormSubmit(event) {
const form = {
gender: "",
}
event.preventDefault();
const data = new FormData(event.target);
form.gender = data.get('gender');
console.log(form);
}
<form method="POST" action="./after-appointment.html" id="myForm" onsubmit="onFormSubmit(event)">
<div class="d-flex btn-group" role="group" aria-label="Basic outlined example">
<button id="gender-0" type="button" class="btn btn-outline-primary gender" onclick="onGenderChange(event)" value="male">Male</button>
<button id="gender-1" type="button" class="btn btn-outline-primary gender" onclick="onGenderChange(event)" value="female">Female</button>
<button id="gender-2" type="button" class="btn btn-outline-primary gender" onclick="onGenderChange(event)" value="other">Other</button>
</div>
<div class="py-5 d-flex justify-content-center">
<button type="submit" class="btn btn-dark-blue text-light">Submit</button>
</div>
</form>
Since you are giving an 'active' class only to the good one, you can use the document.querySelector method to get the element's value within the onFormSubmit function.
function onFormSubmit(event) {
const selectedGender = document.querySelector("#myForm .active").value;
const form = {
gender: selectedGender,
};
event.preventDefault();
const data = new FormData(event.target);
console.log(form);
}