Search code examples
javascriptformsradio-button

How to show specific value when click on any radio button in console using JavaScript?


I am having difficulty to show a value of selected radio button. When I click on question 1 then result 1 should be display on console but I am getting all the values of radio button.Can anyone help me please? Thanks

html

<form onsubmit="return answers(event)">
    <label>Question 1</label>
    <input type="radio" class="question" value="1">
    <label>Question 2</label>
    <input type="radio" class="question" value="2">
    <label>Question 3</label>
    <input type="radio" class="question" value="3">

    <button type="submit">Submit</button>
</form>

JavaScript

<script>

    function answers(event)
    {
        var q = document.querySelectorAll('.question');
        [...q].forEach(question =>{

            console.log(question.value);
        });

        event.preventDefault();
    }
</script>

Solution

  • You could check to see if it is checked with question.checked.

    function answers(event)
        {
            var q = document.querySelectorAll('.question');
            [...q].forEach(question =>{
                if(question.checked){
                    console.log(question.value);
                }
            });
    
            event.preventDefault();
        }
    

    You might also want to add names to all the radios, because the idea of radios is that only one of them can be ticked at a time. name does that for you:

    <form onsubmit="return answers(event)">
        <label>Question 1</label>
        <input type="radio" class="question" value="1" name="question">
        <label>Question 2</label>
        <input type="radio" class="question" value="2" name="question">
        <label>Question 3</label>
        <input type="radio" class="question" value="3" name="question">
    
        <button type="submit">Submit</button>
    </form>