Reputation: 1095
Hello how can i use the queryselector to read two values from a radio button and store the values in array in javascript. Example of the code below is:
<input type="radio" name="one" value="correct" class="firstRow"> Option 1 Mark 1: $650
<input type="radio" name="two" value="incorrect" class="secondRow"> Option 1 Mark 2: Twitter<br>
<input type="radio" name="one" value="incorrect" class="firstRow"> Option 2 Mark 1:$550
<input type="radio" name="two" value="incorrect" class="secondRow"> Option 2 Mark 2:Google<br>
<input type="radio" name="one" value="incorrect" class="firstRow"> Option 3 Mark 1:$650
<input type="radio" name="two" value="correct" class="secondRow"> Option 3 Mark 2:$650<br>
<!--button -->
<input type="button" value="Submit & Next Question" onclick="getAnswer3(this.form)" class="firstRow">
<input type="button" value="Cancel & Clear Selection" onclick="clearOptions(this.form)">
Javascript my idea:
function getAnswer3(form) {
var result = [];
//this only reads one value but i need to read 2 values..
var checked = form.querySelector("input[type=radio]:checked");
if(!checked) {
alert('Please select 2 answers..');
}
else{
//reads the values
}
//stores the values in the array..
}
Upvotes: 1
Views: 3473
Reputation: 26706
You need form.querySelectorAll("input[type=radio]:checked");
Keep in mind that what comes back from querySelectorAll
is not really an array, and so doesn't have any of the particularly fun and easy helper methods that typical arrays do.
It does have a length, though.
if checked
is not going to be helpful, though.
You're always going to get a NodeList
back.
The list might have length === 0, but it'll still be a list (and thus still pass the check to see if it exists). Check that length is < 2, instead.
Upvotes: 6