0

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>
  • 1
    Does this answer your question? [How can I check whether a radio button is selected with JavaScript?](https://stackoverflow.com/questions/1423777/how-can-i-check-whether-a-radio-button-is-selected-with-javascript) – Habebit Aug 19 '21 at 10:13
  • I tried this solution but it doesnt eork for dome reason, cant see if i have a syntac erroror what? – Szabi Vojtek Aug 19 '21 at 11:27

1 Answers1

1

This should work!

<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>
<div id="gender-error" style="color: red; display: none">Please select the gender</div>
<button type="submit" onclick="return submit();">Submit</button>

<script>
    function submit() {
        var radios = document.getElementsByName("radio");
        var value = ""
        for (var i = 0, length = radios.length; i < length; i++) {
            if (radios[i].checked) {
                value = radios[i].value;
                break;
            }
        }

        document.getElementById("gender-error").style.display = !value ? "block" : "none";
        alert(value ? "selected " + value : "no value selected");
    }
</script>

Output:

enter image description here

enter image description here

ujjaldey
  • 421
  • 2
  • 5
  • 17
  • Thank you, this should work, i will try it out as soon as i get home. But how can I include this logic in the 2 above mentioned if statements? I want to apply the invalid class if none of the forms are completed and nome of the radio button selected, and if everything is completed and selected, then apply the valid class – Szabi Vojtek Aug 19 '21 at 13:39
  • @SzabiVojtek edited the code. it will show the error message on submit. you can improvise it further based on your need. – ujjaldey Aug 19 '21 at 14:15
  • nope it does not work, i dont know why. I'm missing something or I don't know whats the problem. I want to include in the 2 conditionals if nothing is completed including no radio button is selected give me the error message and if everything is filled out and one of the radio buttons checked then display the success message. But for some reason it does not work – Szabi Vojtek Aug 20 '21 at 08:53
  • It is the same code as I wrote above, I added your lines too which you suggested, but cannot insert it it checkInputs function I want somehting like this if (firstNameInput === '' || lastNameInput === '' || text === '' || if radio button not selected) { display error message } – Szabi Vojtek Aug 23 '21 at 16:01
  • I managed to work it out, I was just having a syntax error...so dumb :))) Thank you for the help – Szabi Vojtek Aug 24 '21 at 09:04