Hi I am trying to make a form, where are the fields are required, including one of two radio buttons, but for some reason the .checked property will not work neither if I am selecting it like this document.querySelector('input[name="radio"]:checked')... What am I not seeing?
As you can see I was trying different approaches but something is missing
let contactForm = document.querySelector('.contact-form');
let firstName = document.getElementById('first-name');
let lastName = document.getElementById('last-name');
let textarea = document.getElementById('message');
// let radioBtn = document.querySelector('input[name="radio"]:checked');
// let firstRadioBtn = document.getElementById('male').checked;
// let secondRadioBtn = document.getElementById('female').checked;
// console.log(firstRadioBtn.value, secondRadioBtn.value);
let submitBtn = document.querySelector('.btn');
let successMsg = document.querySelector('.success-message');
// let radios = document.getElementsByName('radio');
// let formValid = false;
// console.log(radios)
// for (let i = 0; i < radios.length; i++) {
// if (radios[i].checked) {
// formValid = true
// }
// }
function checkInputs() {
let firstNameInput = firstName.value;
let lastNameInput = lastName.value;
let text = textarea.value;
if (firstNameInput === '' || lastNameInput === '' || text === '') {
firstName.className = 'invalid';
lastName.className = 'invalid';
textarea.className = 'invalid';
successMsg.style.backgroundColor = '#e63946';
successMsg.style.visibility = 'visible';
successMsg.innerText = `Please fill in all the required fields`
}
if (firstNameInput !== '' && lastNameInput !== '' && text !== '') {
firstName.className = 'valid';
lastName.className = 'valid';
textarea.className = 'valid';
successMsg.style.backgroundColor = '#52b788';
successMsg.style.visibility = 'visible';
successMsg.innerText = `Thank you for your message ${firstNameInput} ${lastNameInput}`
}
console.log(`${firstName.value} ${lastName.value} \n Gender: ${radios.value} \n Message: ${message.value}`)
}
<div class="radio-btn label">
<label for="radio">Male</label>
<input type="radio" name="radio" id="male" value="male">
<label for="radio">Female</label>
<input type="radio" name="radio" id="female" value="female">
</div>