Quizgame selection doesn't work properly in Javascript - javascript

I tried to create a little quizgame in Javascript and HTML but it doesn't work properly yet. If I select the correct answer and let it validate, i get a wrong output. In my function showExercise I tried to set the possible answers always in a different order when it gets invoked. Thus the user is not able to select the right answers by a pattern. I am thankful for any suggetions and corrections.
Here is my code:
<!DOCTYPE html>
<html>
<head>
<title>Quizgame</title>
</head>
<body>
<h1>Quizgame</h1>
<form>
<fieldset>
<legend id="question">Quizgame</legend>
<input type="radio" name="choice" id="1" value="1">
<label for="1">Placeholder</label><br>
<input type="radio" name="choice" id="2" value="2">
<label for="2">Placeholder</label><br>
<input type="radio" name="choice" id="3" value="3">
<label for="3">Placeholder</label><br>
<input type="radio" name="choice" id="4" value="4">
<label for="4">Placeholder</label><br>
<button onclick="validateInput()">Check</button>
</fieldset>
</form>
<script type="text/javascript">
var exercise = [];
var index = 0;
exercise[index] = {
question: "Convert this binary number 01000001 to a decimal number:",
correctAnswer: "65",
answer: [ "127", "33", "42", "65" ]
};
index++;
exercise[index] = {
question: "How many combinations can you reach with 3 bits?",
correctAnswer: "8",
answer: [ "11", "9", "6", "8" ]
};
function random( from, to )
{
min = from > to ? to : from;
max = to < from ? from : to;
return( Math.floor( Math.random() * (max - min + 1 ) + min ) );
}
function showExercise( val )
{
document.getElementById( "question" ).innerHTML = exercise[val].question;
for( var i = 0; i < 4; i++ )
{
var index = random( 0, 3 - i );
console.log(index);
document.getElementsByTagName( "label" )[i].innerHTML = exercise[val].answer[index];
exercise[val].answer[index] = exercise[val].answer[3 - i];
}
}
randV = random( 0, index );
function validateInput()
{
var radio = document.getElementsByName( "choice" );
for( var i = 0; i < radio.length; i++ )
{
if( radio[i].checked )
{
if( exercise[randV].answer[i] == exercise[randV].correctAnswer[0] )
{
alert("Right");
}
else
{
alert( "Wrong" );
}
break;
}
}
}
showExercise( randV );
</script>
</body>
</html>

The problem in your code is that you are assigning possible answers in random order to the labels for the radio buttons but the index mapping that radio button to the answer it represents in your answer array is lost.
To fix this problem I have made a minimal change to your code to store the mapping in the value attribute of each radio button. Then when the user makes their selection and clicks CHECK the mapping is retrieved for the selected radio button and used to lookup the answer array.
<html>
<head>
<title>Quizgame</title>
</head>
<body>
<h1>Quizgame</h1>
<form>
<fieldset>
<legend id="question">Quizgame</legend>
<input type="radio" name="choice" id="1" value="1">
<label for="1">Placeholder</label><br>
<input type="radio" name="choice" id="2" value="2">
<label for="2">Placeholder</label><br>
<input type="radio" name="choice" id="3" value="3">
<label for="3">Placeholder</label><br>
<input type="radio" name="choice" id="4" value="4">
<label for="4">Placeholder</label><br>
<button onclick="validateInput()">Check</button>
</fieldset>
</form>
<script type="text/javascript">
var exercise = [];
var index = 0;
exercise[index] = {
question: "Convert this binary number 01000001 to a decimal number:",
correctAnswer: "65",
answer: [ "127", "33", "42", "65" ]
};
index++;
exercise[index] = {
question: "How many combinations can you reach with 3 bits?",
correctAnswer: "8",
answer: [ "11", "9", "6", "8" ]
};
function random( from, to )
{
min = from > to ? to : from;
max = to < from ? from : to;
return( Math.floor( Math.random() * (max - min + 1 ) + min ) );
}
function showExercise( val )
{
document.getElementById( "question" ).innerHTML = exercise[val].question;
for( var i = 0; i < 4; i++ )
{
var index = random( 0, 3 - i );
console.log(index);
document.getElementsByTagName( "label" )[i].innerHTML = exercise[val].answer[index];
//Store the original index to the answer option in the
//value attribute of the radio button.
document.getElementById((i+1).toString()).value = index.toString();
exercise[val].answer[index] = exercise[val].answer[3 - i];
}
}
randV = random( 0, index );
function validateInput()
{
var radio = document.getElementsByName( "choice" );
for( var i = 0; i < radio.length; i++ )
{
if( radio[i].checked )
{
//Retrieve the original index from the radio button
// and use it to look up the answer array.
var lOriginalIndex = document.getElementById((i+1).toString()).value;
if( exercise[randV].answer[lOriginalIndex] == exercise[randV].correctAnswer)
{
alert("Right");
}
else
{
alert( "Wrong" );
}
break;
}
}
}
showExercise( randV );
</script>
</body>
</html>

Related

How to sum two results in Javascript

I am new at this and I got stuck.
I want to sum the two results that I get with this code.
$(document).ready(function() {
$('label').click(function() {
var total = 0;
$('.option:checked').each(function() {
total += parseInt($(this).val());
$(this).parent().css('background', 'gold');
});
$('.option:not(:checked)').each(function() {
$(this).parent().css('background', '#fff');
});
$('#total').html(total + ' $');
});
});
function myFunction() {
var x = document.getElementById("myNumber").value;
document.getElementById("demo").innerHTML = x;
if (x == 5 || x == 6 || x == 7) {
document.getElementById("demo").innerHTML = 97 * x;
} else if (x == 8 || x == 9 || x == 10) {
document.getElementById("demo").innerHTML = 87 * x;
} else if (x >= 11) {
document.getElementById("demo").innerHTML = 82 * x
};
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="myNumber">
<button onclick="myFunction()">Sum</button>
<p id="demo"></p>
<br>
<label><input type="checkbox" class="option" value="200" /> Name</label><br />
<label><input type="checkbox" class="option" value="300" /> Blah</label><br />
<label><input type="checkbox" class="option" value="400" /> XYZ</label><br />
<label><input type="checkbox" class="option" value="800" /> Something</label><br />
<label><input type="checkbox" class="option" value="1200" /> Item</label><br />
<br><br> Total :
<div id="total">0 $</div>
<br>
My question is - how to sum the two results and display it in 'Total:' at the end.
And how to remove the 'Sum' button, so you can see the result from the textbox in realtime in 'Total:' ?
Thanks in advance for any help :)
Edit : I need the sum from text box and the checkbox. For example : if the user have entered '5' this number equals 5 * 97 = 485. So '5' + Name(200) should be equals to 685.
Try this. I have defined a new method to calculate total amount. Whenever the checkbox or textbox is changed, the total is updated.
$(document).ready(function() {
document.getElementById("demo").innerHTML = 0;
$('label').click(function() {
$('.option:checked').each(function() {
$(this).parent().css('background', 'gold');
});
$('.option:not(:checked)').each(function() {
$(this).parent().css('background', '#fff');
});
updateTotal();
});
});
function myFunction() {
var x = document.getElementById("myNumber").value;
document.getElementById("demo").innerHTML = x;
if (x == 5 || x == 6 || x == 7) {
document.getElementById("demo").innerHTML = 97 * x;
} else if (x == 8 || x == 9 || x == 10) {
document.getElementById("demo").innerHTML = 87 * x;
} else if (x >= 11) {
document.getElementById("demo").innerHTML = 82 * x
} else {
document.getElementById("demo").innerHTML = 0;
};
updateTotal();
}
function updateTotal(){
var total = 0;
var totalAmount = 0;
$('.option:checked').each(function() {
total += parseInt($(this).val());
});
totalAmount = total + parseInt(document.getElementById("demo").innerHTML);
$('#total').html( totalAmount +' $');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="myNumber" onkeyup="myFunction()">
<p id="demo"></p>
<br>
<label><input type="checkbox" class="option" value="200" /> Name</label><br />
<label><input type="checkbox" class="option" value="300" /> Blah</label><br />
<label><input type="checkbox" class="option" value="400" /> XYZ</label><br />
<label><input type="checkbox" class="option" value="800" /> Something</label><br />
<label><input type="checkbox" class="option" value="1200" /> Item</label><br />
<br><br> Total :
<div id="total">0 $</div>
<br>
Create a new element with ID totalHolder and inside both functions call a third function (e.g. showTotal()) to sum those values:
$(document).ready(function() {
$('label').click(function() {
var total = 0;
$('.option:checked').each(function() {
total += parseInt($(this).val());
$(this).parent().css('background', 'gold');
});
$('.option:not(:checked)').each(function() {
$(this).parent().css('background', '#fff');
});
$('#total').html(total + ' $');
showTotal();
});
});
function myFunction() {
var x = document.getElementById("myNumber").value;
document.getElementById("demo").innerHTML = x;
if (x == 5 || x == 6 || x == 7) {
document.getElementById("demo").innerHTML = 97 * x;
} else if (x == 8 || x == 9 || x == 10) {
document.getElementById("demo").innerHTML = 87 * x;
} else if (x >= 11) {
document.getElementById("demo").innerHTML = 82 * x
};
showTotal();
}
function showTotal(){
var result1= parseInt($('#total').html());
var result2= parseInt($('#demo').html());
$("#totalHolder").html(result1+result2);
}
In order to remove onClick from button, you just need to set a listener:
$(docuemnt).ready(function(){
$("#myNumber").change(function(){
//Call your function inside the listener
myFunction()
})
})
Not sure if this satisfies your issue, but you need to do a couple things.
You should wrap input fields within a form.
Why are you mixing vanilla JS and jQuery? Stick with one or the other.
You should not be afraid to modularize your application with various functions.
Move the element queries out of the processing functions, instead pass their values in.
You can toggle the class in one loop, see below.
/* jQuery plugins */
(function($) {
/** Checks-off one or more checkboxes in a list of elements. */
$.fn.check = function(checked) {
return this.each(function(index, item) {
if (checked) {
$(item).prop('checked', 'checked');
} else {
$(item).removeProp('checked');
}
});
};
})(jQuery);
$(document).ready(function() {
$('#myNumber').val(5); // Set value to 5.
$('.option').slice(0, 1).check(true); // Check the first checkbox.
$('label').on('click', handleUpdate); // Attach a 'click' listener for label
handleUpdate(); // Call the function.
});
function handleUpdate() {
var sum = sumValues();
var num = $('#myNumber').val();
var mult = getMultiplier(num);
var total = num * mult + sum;
$('#total').html(total.toFixed(2) + ' $');
$('#demo').html(mult);
}
function sumValues() {
var total = 0;
$('.option').each(function() {
var isChecked = $(this).is(':checked');
if (isChecked) total += parseInt($(this).val());
$(this).parent().toggleClass('checked', isChecked);
});
return total;
}
function getMultiplier(value) {
if (value < 5) {
return value;
}
switch (value) {
case 5:
case 6:
case 7:
return 97;
case 8:
case 9:
case 10:
return 87;
default:
return 82;
}
}
label {
display: block;
}
.checked {
background : gold !important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="check-form">
<input type="number" id="myNumber">
<button onclick="handleUpdate(); return false;">Sum</button>
<p id="demo"></p>
<label><input type="checkbox" class="option" value="200" /> Name</label>
<label><input type="checkbox" class="option" value="300" /> Blah</label>
<label><input type="checkbox" class="option" value="400" /> XYZ</label>
<label><input type="checkbox" class="option" value="800" /> Something</label>
<label><input type="checkbox" class="option" value="1200" /> Item</label>
</form>
<br>Total :
<div id="total">0 $</div>

What is the best way to combine and evaluate user input through javascript?

(I'm very new to this, please bear with me)
I'm making several modules that require user input and I want to somehow combine the input to produce an output. I was thinking of assigning each option a value and adding them together and creating an if/else statement to determine the output...
For example, if the user selects three options with values 1, 2, 3 and the statement says that any combined value greater than 5 will get a result of "Good", then the selected options will get a response of "Good" because when combined, they equal 6 (which is >5).
Does anyone know a better way, and/or can you direct me to some reference sites that might have what I'm looking for?
Thank you so much!! Any help is appreciated!!
Are you looking for something like this?
<form id="module1">
<input name="option1" type="checkbox" value="Orange"> Orange
<input name="option2" type="checkbox" value="Banana"> Banana
<input name="option3" type="checkbox" value="Apple"> Apple
<input name="option4" type="checkbox" value="Mango"> Mango
<input name="option5" type="checkbox" value="Pineapple"> Pineapple
</form>
<button id="evaluate" type="button">Evaluate</button>
<h4 id="result"></h4>
<h5 id="values"></h5>
<script type="text/javascript">
$(document).ready(function () {
var scoreConstants = {
'Mango': 100,
'Banana': 100,
'Pineapple': 200,
'Orange': 50,
'Apple': 250
};
var evalScore = function (selectedValues) {
var totalScore = 0;
$.each(selectedValues, function (k, v) {
totalScore += scoreConstants[v];
});
return totalScore;
}
var getScoreLabel = function (score) {
var scoreValue = 'Score: ';
if (score < 200) {
scoreValue += 'Average';
} else if (score >= 200 && score < 500) {
scoreValue += 'Good';
} else if (score >= 500) {
scoreValue += 'Excellent!';
}
return scoreValue;
}
$('body').on('click', '#evaluate', function (e) {
var $selectedValues = $('#module1').find('input:checked');
var selectedValues = [];
$selectedValues.each(function (k, v) {
var $selected = $(v);
selectedValues.push($selected.val());
});
var score = evalScore(selectedValues);
var scoreLabel = getScoreLabel(score);
var valueString = 'Selected: ';
if (selectedValues.length > 0) {
$.each(selectedValues, function (k, v) {
if (k === (selectedValues.length - 1)) {
valueString += v;
} else {
valueString += v + ', '
}
});
} else {
valueString += 'None';
}
var $result = $('#result');
$result.html(scoreLabel);
var $displayValues = $('#values');
$displayValues.html(valueString);
});
});
</script>
See the code working here:
https://jsfiddle.net/0x2L0dek/1
I think you are looking for this.
To see the result, check your console.
<input type="checkbox" class="chk" value=1>1</input><br>
<input type="checkbox" value=2 class="chk">2</input><br>
<input type="checkbox" value=3 class="chk">3</input><br>
<input type="checkbox" value=4 class="chk">4</input><br>
<button id="button1" onclick="checkSum()">Submit</button>
<script>
function checkSum(){
var chk = document.getElementsByClassName('chk');
sum = 0;
for(var i=0; chk[i]; ++i){
if(chk[i].checked){
sum = sum + parseInt(chk[i].value);
}
}
console.log(sum);
if(sum > 5){
console.log("Good");
}
}
</script>

Adding multiple elements by name to a JSON object using Javascript

I have a function that takes in, for example, 10 textboxes worth of values and puts them into a JSON string that I then store in a cookie. I have no issues if I hard code the problem where I'm grabbing the element "assignment[]", but I'd also like to add other text box values to it, say "quizzes[]", as an example, in order to have one long string that I would then convert to a JSON string.
function setObject(name, score)
{
this.name = name;
this.score = score;
}
function setCookie()
{
var cookieName = "assignments";
var cookieValue = document.getElementsByName("assignments[]");
var arr = [];
for(var i=0;i<cookieValue.length;i++)
{
var setObj = new setObject(cookieName + i, cookieValue[i].value);
arr.push(setObj);
}
document.cookie = JSON.stringify(arr);
}
This code above works just fine for just the "name[]" textboxes, but I'd like to be able to add other elements to that same JSON string.
My current output would look like this:
[{"name":"assignments0","score":"1"},{"name":"assignments1","score":"2"},
{"name":"assignments2","score":"3"},{"name":"assignments3","score":"4"}]
My expected output would look like this if I were able to add different textbox arrays through my function:
[{"name":"assignments0","score":"22"},{"name":"assignments1","score":"19"},
{"name":"assignments2","score":"9"},{"name":"assignments3","score":"20"},
{"name":"quizzes0","score":"5"},{"name":"quizzes1","score":"9"}]
Any help in the right direction would be much appreciated.
You can use querySelectorAll() with attribute selector to fetch all the elements like
function setObject(name, score) {
this.name = name;
this.score = score;
}
function setCookie() {
var els = document.querySelectorAll('input[name="assignments[]"],input[name="quizes[]"]');
var arr = [];
for (var i = 0; i < els.length; i++) {
var setObj = new setObject(els[i].name.slice(0, -2) + i, els[i].value);
arr.push(setObj);
}
result1.innerHTML = JSON.stringify(arr, null, 2);
var arr = [].map.call(els, function(el) {
return new setObject(el.name.slice(0, -2) + i, el.value);
});
result2.innerHTML = JSON.stringify(arr, null, 2);
}
setCookie();
<input name="assignments[]" value="1" />
<input name="assignments[]" value="2" />
<input name="assignments[]" value="3" />
<input name="assignments[]" value="4" />
<input name="quizes[]" value="1" />
<input name="quizes[]" value="2" />
<input name="quizes[]" value="3" />
<input name="quizes[]" value="4" />
<pre id="result1"></pre>
<pre id="result2"></pre>
You can assign all the Input Name Arrays to an Array and iterate over it, as in the code below.
var inputs = ["assignments", "quizzes", "three", "four"];
function setObject(name, score) {
this.name = name;
this.score = score;
}
function setCookie() {
var inputs = ["assignments", "quizzes", "three", "four"];
var arr = [];
for (var i = 0; i < inputs.length; i++) {
var cookieName = inputs[i];
var cookieValue = document.getElementsByName(inputs[i] + '[]');
for (var j = 0; j < cookieValue.length; j++) {
var setObj = new setObject(cookieName + j, cookieValue[j].value);
arr.push(setObj);
}
}
result.innerHTML = JSON.stringify(arr, null, 2);
//document.cookie = JSON.stringify(arr);
}
setCookie();
<input name="assignments[]" value="1" />
<input name="assignments[]" value="2" />
<input name="assignments[]" value="3" />
<input name="quizzes[]" value="11" />
<input name="quizzes[]" value="22" />
<input name="quizzes[]" value="33" />
<input name="three[]" value="111" />
<input name="three[]" value="222" />
<input name="three[]" value="333" />
<input name="four[]" value="1111" />
<input name="four[]" value="2222" />
<input name="four[]" value="3333" />
<pre id="result"></pre>
OUTPUT
[
{"name": "assignments0","score": "1"},
{"name": "assignments1","score": "2"},
{"name": "assignments2","score": "3"},
{"name": "quizzes0","score": "11"},
{"name": "quizzes1","score": "22"},
{"name": "quizzes2","score": "33"},
{"name": "three0","score": "111"},
{"name": "three1","score": "222"},
{"name": "three2","score": "333"},
{"name": "four0","score": "1111"},
{"name": "four1","score": "2222"},
{"name": "four2","score": "3333"}
]
Just make it a function?
function getElementsArr(elementsName) {
var elements = document.getElementsByName(elementsName + "[]");
var arr = [];
for(var i=0; i < elements.length;i++)
{
var setObj = new setObject(elementsName + i, elementss[i].value);
arr.push(setObj);
}
return arr;
}
function setCookie(elementNames)
{
var allElements = [];
for(var i = 0; i < elementNames.length; i++) {
allElements.push(getElementsArr(elementNames[i]));
}
document.cookie = JSON.stringify(allElements);
}
setCookie(['assignments', 'quizzes']);

How do I get the sum of radio buttons groups using parameters instead of values

I have multiple sets of radio buttons where the selected values of each set need to be added and displayed to the user. So far I have been changing the values in the function in a switch statement to handle the addition.
<form name="config" id="config">
<div class="row-fluid">
<h3>Memory</h3>
<input type="radio" name="section1" value="4gb" onclick="changePrice(0)" checked>4gb<br>
<input type="radio" name="section1" value="8gb" onclick="changePrice(100)">8gb (+$100)<br>
<input type="radio" name="section1" value="16gb" onclick="changePrice(200)">16gb (+$200)
</div>
<div class="row-fluid">
<h3>Primary Hard Drive</h3>
<input type="radio" name="section2" value="dell" onclick="changePrice(0)" checked>Dell<br>
<input type="radio" name="section2" value="asus" onclick="changePrice(100)">Asus(+$100)
</div>
</form>
<div id="price"></div>
The script I am using right now is
var displayPrice = document.getElementById("price");
var baseNum = 200;
displayPrice.innerHTML = baseNum;
function(changePrice){
var val1, val2;
switch(document.config.section1.value){
case "4gb":
val1 = 0;
break;
case "8gb":
val1 = 100;
break;
case "16gb":
val1 = 200;
break;
default:
val1 = 0;
}
switch(document.config.section2.value){
case "dell":
val1 = 0;
break;
case "asus":
val1 = 100;
break;
default:
val1 = 0;
}
var sum = val1 + val2 + baseNum;
displayPrice.innerHTML = sum;
}
Is there a way I can do these calculations using the parameters passed through the changePrice function (so I don't have to change the values in the switch statements)?
Here's how to do this without jQuery.
You'll need to tell the changePrice function which section it should change the price for so you'll need to change the calls to look like this changePrice(1, 100) where 1 is the section and 100 is the price change. Then you can collect all the section prices individually and sum them like so:
var displayPrice = document.getElementById("price");
var baseNum = 200;
displayPrice.innerHTML = baseNum;
var sections = {};
function changePrice(section,val){
// add or update the section value
sections[section] = val;
// start with the base price
var sum = baseNum;
// loop over all the sections and add them to the base price
for(var key in sections) {
sum = sections[key] + sum;
}
displayPrice.innerHTML = sum;
}
Here's a jsfiddle
If you change your function definition to the following, it will take in your parameter.
function changePrice(val1)
If you could change your the value attribute on each of your input fields to contain your increment value, it would make the process of calculating your sum much easier. (This may not be appropriate to the problem you are trying to solve.
Basic solution with jQuery
var sum = $("input[name=section1]").val() + $("input[name=section2]").val();
If your list is very long, you could iterate over your radio button sets with jQuery
var sum = 0;
$("input[type=radio]").each(function(){sum += $(this).val();});
<html>
<head>
<script type="text/javascript">
function DisplayPrice(price){
var val1 = 0;
for( i = 0; i < document.form1.R1.length; i++ ){
if( document.form1.R1[i].checked == true ){
val1 = document.form1.R1[i].value;
}
}
var val2 = 0;
for( i = 0; i < document.form2.R2.length; i++ ){
if(document.form2.R2[i].checked == true ){
val2 = document.form2.R2[i].value;
}
}
var sum=parseInt(val1) + parseInt(val2);
document.getElementById('totalSum').innerHTML=sum;
}
</script>
</head>
<body>
Choose a number:<br>
<form name="form1" id="form1">
<br>
R1 <input id="rdo_1" type="radio" value="5" name="R1" onClick="DisplayPrice(this.value);" checked>5
<br>
R1 <input id="rdo_2" type="radio" value="10" name="R1" onClick="DisplayPrice(this.value);">10
<br>
</form>
Choose another number:<br>
<form name="form2" id="form2">
<br>
R2 <input id="rdo_1" type="radio" value="15" name="R2" onClick="DisplayPrice(this.value);" checked>15
<br>
R2 <input id="rdo_2" type="radio" value="20" name="R2" onClick="DisplayPrice(this.value);">20
<br>
</form>
Your total is Rs = <span name="totalSum" id="totalSum" > 20</span>
</body>
</html>

Checking radio buttons according to an Array

I have an array containing four numbers:
var players = [0,3,4,2];
I have some radio buttons to select a name:
<h3 id="question">Which player would you like?</h3>
<input type="radio" name="choice" value="0" id="answ1">
<label for="choice" id="choice_1">John</label>
<br>
<input type="radio" name="choice" value="1" id="answ2">
<label for="choice" id="choice_2">Wayne</label>
<br>
<input type="radio" name="choice" value="2" id="answ3">
<label for="choice" id="choice_3">Steven</label>
<br>
<input type="radio" name="choice" value="3" id="answ4">
<label for="choice" id="choice_4">Jack</label>
<br>
<button id="back">Back</button>
<button id="next">Next</button>
When the radio buttons display I would like the first radio button to be checked i.e. The player John. I know I could simply set autofocus or use jQuery but I want to do it with vanilla Javascript. The idea is that the player names will change dynamically and the player will be selected based on the value in the array i.e. number 3 of the second set of players will be chosen.
Thanks, any help appreciated.
EDIT:
John will be chosen because the first value of the array is 0 and John is the first choice i.e. 0 = 1st choice, 1 = second choice etc
You need to increment/decrement an index value when the Next/Back buttons are clicked, and then set the checked property to true for the radio button with that index.
var players = [0, 3, 4, 2, 1];
var i = 0;
var choices = document.querySelectorAll('input[name="choice"]');
choices[players[i]].checked = true;
document.getElementById('back').onclick = function () {
if (i > 0) {
i--;
choices[players[i]].checked = true;
}
}
document.getElementById('next').onclick = function () {
if (i < players.length - 1) {
i++;
choices[players[i]].checked = true;
}
}
DEMO
You can try my approach using array.indexOf
var players = [0, 3, 4, 2];
var ins = document.getElementsByName('choice');
for (var i = 0; i < ins.length; i++) {
if (players.indexOf(parseInt(ins[i].value, 10)) > -1) {
ins[i].checked = true;
}
}
FYI:
The radio button is grouped under the name check so multiple
select is not going to work in your case.
This code will fail in older version of IE and here is the workaround.
You can do this like this:
var players = [0,3,4,2];
var firstValue = players[0];
var firstInput = document.querySelector("input[type=radio][name=choice][value='"+firstValue+"']");
firstInput.checked = true;
var players = [0,3,1,2];
var currentPosInArray = 0;
window.onload = function() {
ChangeSelectedRadio();
}
function ChangeSelectedRadio() {
var radio = document.querySelectorAll("input[type='radio']");
var arrItem = players[currentPosInArray];
for (var i =0; i< radio.length; i++ ){
radio[i].checked = false;
}
if (radio[arrItem]) {
radio[arrItem].checked = true;
}
}
function ChangeSelection(forward) {
if (forward) {
currentPosInArray++;
}
else {
currentPosInArray--;
}
if (currentPosInArray < 0) {
currentPosInArray = players.length -1; //if is in first pos and click "Back" - go to last item in array
}
else if (currentPosInArray >= players.length) {
currentPosInArray = 0; //if is in last position and click "Next" - go to first item in array
}
ChangeSelectedRadio();
}
where ChangeSelection(forward) is event to buttons.
DEMO: http://jsfiddle.net/9RWsp/1/

Categories

Resources