Get the value of radio input with javascript

Asked

Viewed 7,180 times

5

I’m trying to ask a quiz of questions and I’d like to take the value of input radio, which are the answer options. Any tips on how to do this using javascript only?

<form>
	<h3>1. Which tag should used to represent the "header" of a document?</h3>
	<ul>
		<li><input type="radio" name="q1" value="a">head</li>
		<li><input type="radio" name="q1" value="b">header</li>
		<li><input type="radio" name="q1" value="c">heading</li>
	        <li><input type="radio" name="q1" value="d">main</li>
	</ul>		
	<button id="submit">Submit</button>
</form>

2 answers

8


You can use the javascript method queryselector and match the javascript selectors:

document.querySelector('input[name="q1"]:checked').value;

5

To capture the input's of form using only javascript:

<form id="form">
    <h3>1. Which tag should used to represent the "header" of a document?</h3>
    <ul>
        <li><input type="radio" name="q1" value="a">head</li>
        <li><input type="radio" name="q1" value="b">header</li>
        <li><input type="radio" name="q1" value="c">heading</li>
        <li><input type="radio" name="q1" value="d">main</li>
    </ul>
    <button id="btn-salvar" type="submit">Submit</button>
</form>
<script>
    var form = document.querySelector('#form');
    var botao = document.querySelector('#btn-salvar');

    botao.addEventListener('click', function (event) {
        event.preventDefault();
        console.log(form.q1.value);
    });
</script>

Note: The event.preventDefault() avoid normal loading of the page containing a form button-like submit. If you do not want this to happen, you should call event within its anonymous function, to prevent the form from reloading the page.

  • 1

    It worked out here! Thanks! You could only explain this function to me event.preventDefault() ?

  • 1

    updated the response with the observation of the meaning of event.preventDefault().

Browser other questions tagged

You are not signed in. Login or sign up in order to post.