Get the value of the input radio with javascript

5

I'm trying to quiz you and would like to get the value of the input radio, which are the answer options. Any tips on how I can 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>
    
asked by anonymous 12.07.2017 / 21:10

2 answers

4

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

document.querySelector('input[name="q1"]:checked').value;
    
12.07.2017 / 21:23
5

To capture input's of form using just 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: event.preventDefault() is for behavior to prevent normal page load containing form with button submit type. If you do not want this to happen, you should call event inside your anonymous function, to prevent form from reloading the page.

    
12.07.2017 / 21:20