Automatically populate input field with data on clicking radio buttons - javascript

When the user selects a radio button in the 2 categories Plan details and Plan Duration the input field should populate with the relevant data through JavaScript.
Please check the html markup and JavaScript below and suggest corrections or an alternate method that would work.
<h3 class="fltClear">Plan Details</h3>
<div id="spryradio1">
<dt>Plan Type: <span class="required">*</span></dt>
<dd>
<label>
<input type="radio" name="RadioGroup1" value="Silver" id="RadioGroup1_0" onClick="changeplanprice();" class="RadioGroup1" />
Silver</label>
<br>
<label>
<input type="radio" name="RadioGroup1" value="Gold" id="RadioGroup1_1" onClick="changeplanprice();" class="RadioGroup1" />
Gold</label>
<br>
<label>
<input type="radio" name="RadioGroup1" value="Platinum" id="RadioGroup1_2" onClick="changeplanprice();" class="RadioGroup1" />
Platinum</label>
<br>
<label>
<input type="radio" name="RadioGroup1" value="All-in-one" id="RadioGroup1_3" onClick="changeplanprice();" class="RadioGroup1" />
All-in-one</label>
<br>
<span class="radioRequiredMsg">Please make a selection.<span class="hint-pointer"> </span></span>
</dd>
</div>
<!--Plan Duration-->
<div id="spryradio2">
<dt>Plan Duration: <span class="required">*</span></dt>
<dd>
<label>
<input type="radio" name="RadioGroup2" value="Yearly" id="RadioGroup2_0" onClick="changeplanprice();" class="RadioGroup2" />
Yearly</label>
<br>
<label>
<input type="radio" name="RadioGroup2" value="Quaterly" id="RadioGroup2_1" onClick="changeplanprice();" class="RadioGroup2" />
Quaterly</label>
<br>
<label>
<input type="radio" name="RadioGroup2" value="Monthly" id="RadioGroup2_2" onClick="changeplanprice();" class="RadioGroup2" />
Monthly</label>
<br>
<label>
<input type="radio" name="RadioGroup2" value="Other" id="RadioGroup2_3" onClick="changeplanprice();" class="RadioGroup2" />
Other</label>
<br>
<span class="radioRequiredMsg">Please make a selection.<span class="hint-pointer"> </span></span>
</dd>
</div>
<!--Plan Price-->
<div>
<script>
function changeplanprice() {
var plantype=document.getElementByClassName('RadioGroup1').value;
var planduration=document.getElementByClassName('RadioGroup2').value;
if(plantype=="Silver") {
if(planduration=="Monthly") {
document.getElementById('Price').value='£ 39.98';
document.getElementById('Price').readOnly=true;
}
else if(planduration=="Quaterly") {
document.getElementById('Price').value='£ 79.98';
document.getElementById('Price').readOnly=true;
}
else if(planduration=="Yearly") {
document.getElementById('Price').value='£ 124.98';
document.getElementById('Price').readOnly=true;
}
else if(planduration=="Other") {
document.getElementById('Price').value='';
document.getElementById('Price').readOnly=false;
}
}
else if(plantype=="Gold") {
if(planduration=="Monthly") {
document.getElementById('Price').value='£ 49.98';
document.getElementById('Price').readOnly=true;
}
else if(planduration=="Quaterly") {
document.getElementById('Price').value='£ 99.98';
document.getElementById('Price').readOnly=true;
}
else if(planduration=="Yearly") {
document.getElementById('Price').value='£ 179.98';
document.getElementById('Price').readOnly=true;
}
else if(planduration=="Other") {
document.getElementById('Price').value='';
document.getElementById('Price').readOnly=false;
}
}
else if(plantype=="Platinum") {
if(planduration=="Monthly") {
document.getElementById('Price').value='£ 59.98';
document.getElementById('Price').readOnly=true;
}
else if(planduration=="Quaterly") {
document.getElementById('Price').value='£ 199.98';
document.getElementById('Price').readOnly=true;
}
else if(planduration=="Yearly") {
document.getElementById('Price').value='£ 279.98';
document.getElementById('Price').readOnly=true;
}
else if(planduration=="Other") {
document.getElementById('Price').value='';
document.getElementById('Price').readOnly=false;
}
} }
</script>
<div>
<dt><label for="Price">Plan Price:</label></dt>
<dd class="bg"><input type="text" name="Price" id="Price" size="80" class="input" readonly="readonly" />
</dd>
</div>

First suggestion that I will give is to have single
document.getElementById('Price').readOnly=true;
This will make your code more readable.
Second suggestion is that you can have 2 arrays one for plantype and other for planduration, and the radio-buttons instead of text, have array index as value.
This will not only make your code more readable, but also more manageable.
Suppose if you have to add one planduration, you will have to add the same condition for all plantypes, where there is a possibility of missing out one case.

Your function could use a little bit of cleanup, but there is one problem that I see. You are using document.getElementByClassName(' ... ').value;. This isn't correct. The function is actually document.getElementsByClassName (note Elements is plural). This function returns an array of all elements with that class name. So you cannot call .value directly on that. You would need to loop through the array of elements to find which element is checked and take the value of that.
Given that all the radio buttons of one group have the same name, and there is another function, document.getElementsByName, there is no reason to use getElementsByClassName.
I would change your function. This is tested and works, and is more easily scalable, in case you come up with new pricing options. All you would have to do is add on to the prices object:
function changeplanprice() {
var plantype;
var plantypes = document.getElementsByName('RadioGroup1');
for (var i=0; i < plantypes.length; i++) {
if (plantypes[i].checked)
plantype = plantypes[i].value;
}
var planduration;
var plandurations = document.getElementsByName('RadioGroup2');
for (i = 0; i < plandurations.length; i++) {
if (plandurations[i].checked)
planduration = plandurations[i].value;
}
if (plantype === undefined || planduration === undefined)
return;
document.getElementById('Price').readOnly = (planduration != "Other");
var prices = {
"Silver":{
"Monthly":"£ 39.98",
"Quarterly":"£ 79.98",
"Yearly":"£ 124.98",
"Other":""
},
"Gold":{
"Monthly":"£ 49.98",
"Quarterly":"£ 99.98",
"Yearly":"£ 179.98",
"Other":""
},
"Platinum":{
"Monthly":"£ 59.98",
"Quarterly":"£ 199.98",
"Yearly":"£ 279.98",
"Other":""
},
"All-in-one":{
"Monthly":"...", /* prices weren't provided for All-in-one in the example */
"Quarterly":"...",
"Yearly":"...",
"Other":""
}
};
document.getElementById('Price').value = prices[plantype][planduration];
}

Related

Condition: input:checked with the same class

I would like to have a little help on an enigma that I have.
I have a button that changes according to the number of input:checked
but I would like to add a condition which is: select of the checkboxes of the same class.
for example can I have 2 or more input.
<input class="banana" type="checkbox" value="Cavendish">
<input class="banana" type="checkbox" value="Goldfinger">
<input class="chocolato" type="checkbox" value="cocoa powder">
<input class="chocolato" type="checkbox" value="milk chocolate">
<input class="apple" type="checkbox" value="honneycrisp">
<input class="apple" type="checkbox" value="granny smith">
I can't use attribute name or value. it is not possible to modify the inputs.
the condition:
$('input[type="checkbox"]').click(function(){
if($('input[type="checkbox"]:checked').length >=2){
////////
if (my classes are the same) {
$('#btn').html("click me").prop('disabled', false);
} else {
$('#btn').html("too bad").prop('disabled', true);
}
//////
}
I try with
var checkClass = [];
$.each($("input[type="checkbox"]:checked"), function() {
checkClass.push($(this).attr('class'));
});
I don't know if I'm going the right way or if I'm complicating the code but a little help would be welcome. For the moment my attempts have been unsuccessful.
The following function will reference the first checkbox that's checked className and enable each checkbox that has said className whilst disabling all other checkboxes. Details are commented in Snippet.
// All checkboxes
const all = $(':checkbox');
// Any change event on any checkbox run function `matchCategory`
all.on('change', matchCategory);
function matchCategory() {
// All checked checkboxes
const checked = $(':checkbox:checked');
let category;
// if there is at least one checkbox checked...
if (checked.length > 0) {
// ...enable (.btn)...
$('.btn').removeClass('off');
// ...get the class of the first checked checkbox...
category = checked[0].className;
// ...disable ALL checkboxes...
all.attr('disabled', true);
// ...go through each checkbox...
all.each(function() {
// if THIS checkbox has the class defined as (category)...
if ($(this).is('.' + category)) {
// ...enable it
$(this).attr('disabled', false);
// Otherwise...
} else {
// ...disable and uncheck it
$(this).attr('disabled', true).prop('checked', false);
}
});
// Otherwise...
} else {
// ...enable ALL checkboxes...
all.attr('disabled', false);
// ...disable (.btn)
$('.btn').addClass('off');
}
return false;
}
.off {
pointer-events: none;
opacity: 0.4;
}
<input class="beverage" type="checkbox" value="Alcohol">
<label>🍸</label><br>
<input class="beverage" type="checkbox" value="Coffee">
<label>☕</label><br>
<input class="dessert" type="checkbox" value="cake">
<label>🍰</label><br>
<input class="dessert" type="checkbox" value="Ice Cream">
<label>🍨</label><br>
<input class="appetizer" type="checkbox" value="Salad">
<label>🥗</label><br>
<input class="appetizer" type="checkbox" value="Bread">
<label>🥖</label><br>
<button class='btn off' type='button '>Order</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
some thing like that ?
const
bt_restart = document.getElementById('bt-restart')
, chkbx_all = document.querySelectorAll('input[type=checkbox]')
;
var checked_class = ''
;
bt_restart.onclick = _ =>
{
checked_class = ''
chkbx_all.forEach(cbx=>
{
cbx.checked=cbx.disabled=false
cbx.closest('label').style = ''
})
}
chkbx_all.forEach(cbx=>
{
cbx.onclick = e =>
{
if (checked_class === '') checked_class = cbx.className
else if (checked_class != cbx.className )
{
cbx.checked = false
cbx.disabled = true
cbx.closest('label').style = 'color: grey'
}
}
})
<button id="bt-restart">restart</button> <br> <br>
<label> <input class="banana" type="checkbox" value="Cavendish" > a-Cavendish </label> <br>
<label> <input class="banana" type="checkbox" value="Goldfinger" > a-Goldfinger </label> <br>
<label> <input class="chocolato" type="checkbox" value="cocoa powder" > b-cocoa powder </label> <br>
<label> <input class="chocolato" type="checkbox" value="milk chocolate"> b-milk chocolate </label> <br>
<label> <input class="apple" type="checkbox" value="honneycrisp" > c-honneycrisp </label> <br>
<label> <input class="apple" type="checkbox" value="granny smith" > c-granny smith </label> <br>
In fact it's like a Matching Pairs card game
this answer is without global checked_group variable, and respecting epascarello message about data attribute see also usage.
Adding a repentance on uncheck elements
const
bt_restart = document.getElementById('bt-restart')
, chkbx_all = document.querySelectorAll('input[type=checkbox]')
;
function clearGame()
{
chkbx_all.forEach(cbx=>
{
cbx.checked = cbx.disabled = false
cbx.closest('label').style = ''
})
}
bt_restart.onclick = clearGame
chkbx_all.forEach(cbx=>
{
cbx.onclick = e =>
{
let checkedList = document.querySelectorAll('input[type=checkbox]:checked')
if (cbx.checked)
{
let checked_group = ''
checkedList.forEach(cEl=>{ if (cEl !== cbx) checked_group = cEl.dataset.group })
if (checked_group === '') checked_group = cbx.dataset.group
else if (checked_group !== cbx.dataset.group )
{
cbx.checked = false // you need to uncheck wrong group checkboxes for preserving checkedList
cbx.disabled = true
cbx.closest('label').style = 'color: grey'
}
}
else if (checkedList.length === 0) // case of cheked repentir
clearGame()
}
})
<button id="bt-restart">restart</button> <br> <br>
<label> <input data-group="banana" type="checkbox" value="Cavendish" > a-Cavendish </label> <br>
<label> <input data-group="banana" type="checkbox" value="Goldfinger" > a-Goldfinger </label> <br>
<label> <input data-group="chocolato" type="checkbox" value="cocoa powder" > b-cocoa powder </label> <br>
<label> <input data-group="chocolato" type="checkbox" value="milk chocolate"> b-milk chocolate </label> <br>
<label> <input data-group="apple" type="checkbox" value="honneycrisp" > c-honneycrisp </label> <br>
<label> <input data-group="apple" type="checkbox" value="granny smith" > c-granny smith </label> <br>

Display different divs using input checkbox

I want to use 3 input checkbox to display 3 different div. I am using this code but the only one working is "Course 1" and I can't figure out why. I guess it is something pretty easy, but I can't see it:
document.getElementById('checkbox1');
checkbox1.onchange = function() {
if (checkbox1.checked) {
course1.style.display = 'block';
} else {
course1.style.display = 'none';
}
};
document.getElementById('checkbox2');
checkbox2.onchange = function() {
if (checkbox2.checked) {
course2.style.display = 'block';
} else {
course2.style.display = 'none';
}
};
document.getElementById('checkbox3');
checkbox3.onchange = function() {
if (checkbox3.checked) {
course3.style.display = 'block';
} else {
course3.style.display = 'none';
}
};
<form>
<label class="switch">
<input type="checkbox" id="checkbox1" checked="true"> Course 1
</label>
</form>
<form>
<label class="switch">
<input type="checkbox" id="checkbox2" checked="true"> Course 2
</label>
</form>
<form>
<label class="switch">
<input type="checkbox" id="checkbox3" checked="true"> Course 3
</label>
</form>
<br>
<div id="course1"> Text course 1
</div>
<br>
<div id="course2"> Text course 2
</div>
<br>
<div id="course2"> Text course 3
</div>
Example: https://codepen.io/antonioagar1/pen/dqGaoO
You can try this simple code instead of your own code:
document.addEventListener("change", function(ev){
if(ev.target.id.substr(0,8)=="checkbox") document.querySelector("[id='course"+ev.target.getAttribute("id").slice(-1)+"']").style.display=ev.target.checked?"block":"none";
});
you have two div with id course2. first, change it to course3 and then try.
Check result online

get radio value with javascript

hello everyone I can't get the radio input value here is my code :
the alert isn't running
I want to do a real time calculation that shows the total to pay and I couldn't handle the radio values I appreciate your help thanks :D
function transfer()
{
var vip=document.getElementByName('mercedes');
for (var i = 0, length = vip.length; i < length; i++)
{
if (vip[i].checked)
{
alert(vip[i].value);
break;
}
}
}
<div class="form-group">
<label for="f1-about-yourself">Mercedes VIP transfer*:</label> <br>
<input type="radio" name="mercedes" id="yes" value="yes"
onclick="transfer()">
<label for="yes">Yes:</label>
<input type="radio" name="mercedes" id="no" value="no" checked="" onclick="transfer()">
<label for="no">No:</label>
</div>
function transfer()
{
var vip=document.getElementsByName('mercedes');
for (var i = 0, length = vip.length; i < length; i++)
{
if (vip[i].checked)
{
alert(vip[i].value);
break;
}
}
}
<div class="form-group">
<label for="f1-about-yourself">Mercedes VIP transfer*:</label> <br>
<input type="radio" name="mercedes" id="yes" value="yes"
onclick="transfer()">
<label for="yes">Yes:</label>
<input type="radio" name="mercedes" id="no" value="no" onclick="transfer()">
<label for="no">No:</label>
</div>
In addition to the already given answer that did fix the OP's problem the OP might think about separation of markup and code, thus not using inline code within html element markup.
Making use of the html form element that then hosts specific form controls like input, button etc. is highly advised too. Making
use of the "DOM Level 0" form collection also is not outdated. Event delegation as provided with the next example for instance helps if there will be other controls added to a form dynamically - one does not need to take care about registering event handlers to each newly appended form control. And last, registering to 'change' events will capture every change to the radio collection ...
function isMercedesTransferType(elmNode) {
return ((elmNode.type === 'radio') && (elmNode.name === 'mercedes'));
}
function handleVipTransferChange(evt) {
var elmNode = evt.target;
if (isMercedesTransferType(elmNode) && elmNode.checked) {
console.log('handleVipTransferChange [name, value] : ', elmNode.name, elmNode.value);
}
}
function initializeVipTransfer() {
document.forms['mercedes-vip-transfer'].addEventListener('change', handleVipTransferChange, false);
}
initializeVipTransfer();
.as-console-wrapper { max-height: 100%!important; top: 70px; }
<form class="form-group" name="mercedes-vip-transfer">
<legend>Mercedes VIP transfer*:</legend>
<label>
<input type="radio" name="mercedes" value="yes">
<span>Yes</span>
</label>
<label>
<input type="radio" name="mercedes" value="no">
<span>No</span>
</label>
</form>
Another way of dealing with initializing the required form controls directly will be demonstrated hereby ...
function isMercedesTransferType(elmNode) {
return ((elmNode.type === 'radio') && (elmNode.name === 'mercedes'));
}
function handleVipTransferChange(evt) {
var elmNode = evt.target;
if (elmNode.checked) {
console.log('handleVipTransferChange [name, value] : ', elmNode.name, elmNode.value);
}
}
function initializeVipTransfer() {
var list = document.forms['mercedes-vip-transfer'].elements['mercedes'];
Array.from(list).filter(isMercedesTransferType).forEach(function (elmNode) {
elmNode.addEventListener('change', handleVipTransferChange, false);
});
}
initializeVipTransfer();
.as-console-wrapper { max-height: 100%!important; top: 70px; }
<form class="form-group" name="mercedes-vip-transfer">
<legend>Mercedes VIP transfer*:</legend>
<label>
<input type="radio" name="mercedes" value="yes">
<span>Yes</span>
</label>
<label>
<input type="radio" name="mercedes" value="no">
<span>No</span>
</label>
</form>
... and just in order to round it up, if there is an "up to date" DOM, one might consider making use of modern DOM queries via querySelector and/or querySelectorAll ...
function handleVipTransferChange(evt) {
var elmNode = evt.target;
if (elmNode.checked) {
console.log('handleVipTransferChange [name, value] : ', elmNode.name, elmNode.value);
}
}
function initializeVipTransfer() {
var list = document.querySelectorAll('#mercedes-vip-transfer [type="radio"][name="mercedes"]');
Array.from(list).forEach(function (elmNode) {
elmNode.addEventListener('change', handleVipTransferChange, false);
});
}
initializeVipTransfer();
.as-console-wrapper { max-height: 100%!important; top: 70px; }
<form class="form-group" id="mercedes-vip-transfer">
<legend>Mercedes VIP transfer*:</legend>
<label>
<input type="radio" name="mercedes" value="yes">
<span>Yes</span>
</label>
<label>
<input type="radio" name="mercedes" value="no">
<span>No</span>
</label>
</form>

coding for last radio button text input

I have a list of 5 radio buttons, with the last radio button to select a manual entry text (an "other" option). I can't seem to get the form to work for all 5 possibilities - either it returns the radio value or the written value (currently only the written value and not any of the preset radio values). Can't get it to work for all of 5 possible returns.
Here's the javascript to either select text or clear it when unselected:
<script type= "text/javascript" >
function HandleRadioOtherBox(grp, txt)
{
var x, len = grp.length;
for (x =0; x<len; ++x)
{
if (grp[x].checked) break;
}
if (x < len && grp[x].value == txt.name)
{
txt.disabled = false;
txt.select();
txt.focus();
}
else
{
txt.value = "";
txt.disabled = true;
}
return true;
}
window.onload = function ()
{
var ele = document.forms[0].elements;
return HandleRadioOtherBox(ele['OPS'], ele['Country']);
}
</script>
And here, the HTML radio button portion:
<tr valign="top">
<td class="style3">Country: </td>
<td class="copy">
<input type="radio" name="OPS" value="United States" checked="checked"
onclick="return HandleRadioOtherBox(OPS, Country)" /> United States
<input type="radio" name="OPS" value="Canada"
onclick="return HandleRadioOtherBox(OPS, Country)" /> Canada
<input type="radio" name="OPS" value="England"
onclick="return HandleRadioOtherBox(OPS, Country)" /> England
<input type="radio" name="OPS" value="Australia"
onclick="return HandleRadioOtherBox(OPS, Country)" /> Australia <br />
<input type="radio" name="OPS" value="Country"
onclick="return HandleRadioOtherBox(OPS, Country)" /> Other Country:
<input type='text' name="Country" id="Country" maxlength='80' />
</td>
</tr>
Have spent many, many hours with not much of a hole made in the cement (yet). :-)
Help!
You can write a single function for your form which checks for two events:
radio button check
text input blur
and then gives an appropriate response based on which radio button registered a check event or whether the text input registered a blur event:
var radioButtons = document.querySelectorAll('input[type="radio"]');
var otherCountryRadio = document.querySelector('.other-country input[type="radio"]');
var otherCountryText = document.querySelector('.other-country input[type="text"]');
function returnValue() {
if (this === otherCountryRadio) {
otherCountryText.focus();
}
else {
if (this.value.match(/\w/)) {
console.log(this.value);
}
}
}
for (var i = 0; i < radioButtons.length; i++) {
radioButtons[i].addEventListener('change', returnValue, false);
}
otherCountryText.addEventListener('blur', returnValue, false);
div {
margin: 12px;
}
.other-country input[type="text"] {
visibility: hidden;
}
.other-country input:checked + input[type="text"] {
visibility: visible;
}
<form>
<div class="top-countries">
<label><input type="radio" name="OPS" value="United States" checked="checked" /> United States</label>
<label><input type="radio" name="OPS" value="Canada" /> Canada</label>
<label><input type="radio" name="OPS" value="England" /> England</label>
<label><input type="radio" name="OPS" value="Australia" /> Australia</label>
</div>
<div class="other-country">
<label>
<input type="radio" name="OPS" value="Other" /> Other Country
<input type="text" name="Country" />
</label>
</div>
</form>

javascript conditional statement for a group of radio buttons

I want to make an online test, but i have some problems with the code below.
I want it to mark the correct and wrong answers, and show the score, when the button is pressed.
Now I have the following problem: I want the first switch statement to be only for the first group of radio buttons, the second switch statement for the second group of buttons, and so on.
How could I do that? When I run the code now, the colors change even though none of the radio buttons is checked, or when a button in only one of the groups is checked.
function showScore() {
var check;
var total = 0;
var yourmark = "your score is ";
switch (document.getElementById('q12').checked) {
case true:
total = total + 1;
document.getElementById('text1').style.color = "green";
break;
case false:
document.getElementById('text0').style.color = "red";
document.getElementById('text2').style.color = "red";
document.getElementById('text1').style.color = "green";
break;
}
switch (document.getElementById('q13').checked) {
case true:
document.getElementById('text0.1').style.color = "green";
total = total + 1;
break;
case false:
document.getElementById('text1.1').style.color = "red";
document.getElementById('text1.2').style.color = "red";
break;
}
alert(yourmark + total);
}
<input type="radio" name="question1" id="q11" value="false">
<text id="text0">Question 1-first option</text>
<br>
<input type="radio" name="question1" id="q12" value="true">
<text id="text1">Question 1- second option</text>
<br>
<input type="radio" name="question1" value="false">
<text id="text2">Question 1- third option</text>
<br>
<br>
<input type="radio" name="question2" id="q13" value="false">
<text id="text0.1">Question 1-first option</text>
<br>
<input type="radio" name="question2" id="q12" value="true">
<text id="text1.1">Question 1- second option</text>
<br>
<input type="radio" name="question2" value="false">
<text id="text1.2">Question 1- third option</text>
<br>
<button onclick="showScore();">Show my score</button>
Try this:
var questions = document.forms.myForm.getElementsByClassName('question');
document.getElementById('showScore').onclick = function showScore() {
var total = 0,
correct = 0;
for(var i=0; i<questions.length; ++i) {
var chosen = questions[i].querySelector(':checked');
if(chosen) {
questions[i].classList.add('show-score');
correct += chosen.value == 'true';
++total;
}
}
alert("Your score is " + correct + " out of " + total);
};
.question {
margin: 1em 0; /* Separation between questions */
}
.question > label:after { /* Line-break after each answer */
content: '';
display: block;
}
.question.show-score > input[value=true]+label {
color: green;
}
.question.show-score > input[value=false]+label {
color: red;
}
<form name="myForm">
<div class="question">
<input type="radio" name="question1" id="q-1-1" value="false">
<label for="q-1-1">Question 1 - first option</label>
<input type="radio" name="question1" id="q-1-2" value="true">
<label for="q-1-2">Question 1 - second option</label>
<input type="radio" name="question1" id="q-1-3" value="false">
<label for="q-1-3">Question 1 - third option</label>
</div>
<div class="question">
<input type="radio" name="question2" id="q-2-1" value="false">
<label for="q-2-1">Question 2 - first option</label>
<input type="radio" name="question2" id="q-2-2" value="true">
<label for="q-2-2">Question 2 - second option</label>
<input type="radio" name="question2" id="q-2-3" value="false">
<label for="q-2-3">Question 2 - third option</label>
</div>
<button id="showScore">Show my score</button>
</form>
Note those changes:
I have removed inline event listener from HTML, and added it using JS
I removed those ugly <br> and used CSS instead
I used <label> instead of invalid <text>. With <label>, you can also check a radio by clicking the text.
Instead of setting the color of correct/wrong answers with JS, I used CSS.
Well, ehr: group them. There's a lot wrong with your code and html. Id's are inconsistent, you are using inline event handlers, the code itself is bulky etc.
If you group the radiobuttons with a surrounding div, use consistent id's, labels instead of the <text> tag, leave the label-formatting to css and use querySelector[All], the code can be much shorter, really. Something like:
document.querySelector('body').addEventListener('click', showScore);
function showScore(e) {
var from = e.target || e.srcElement, fromtype = from.type;
if ( !(fromtype && /radio/i.test(fromtype)) ) { return true; }
var score = document.querySelectorAll('input:checked[value=true]').length;
// .. do stuff with [score]
}
It's demonstrated in this jsFiddle

Categories