Javascript Form score update on submit - javascript

I have trouble figuring out what's happening here. This is a little quiz I have written using form with radio buttons. It's my first time playing around with forms and javascript. I don't understand why the score is always 1. The problem is that on submit, it only updates to whatever the +score for the 2nd answer is. When I remove 2nd +score the value remains 0, and when I change the +score for 2nd answer to 10, the score is 10. Would be really grateful for help.
Javascript code:
function validateRadio(obj, correct) {
var result = 0;
var i;
var l = obj.lenght;
for (i = 0; i < l; i++) {
if(obj[i].checked == true && obj[i].value == correct) {
result = 1;
}
}
if (!result && obj[i].value == correct) {
result = 1;
}
return result;
}
function validateSubmit(obj) {
//configuration
var score = 0;
//cache DOM
var scoreMsg = document.getElementById('scoreMsg');
//Score update on correct asnwer
if (validateRadio(obj.radAns1, 2)) {
score += 1;
}
if (validateRadio(obj.radAns2, 1)) {
score += 1;
}
if (validateRadio(obj.radAns3, 3)) {
score += 1;
}
if (validateRadio(obj.radAns4, 5)) {
score += 1;
}
if (validateRadio(obj.radAns5, 4)) {
score += 1;
}
scoreMsg.innerHTML = score;
}
HTML code;
<form onsubmit="validateSubmit(this);return false;" action='#'>
<div id="pytanie 1" class="pytania">
<span class="pytanie-numer">Pytanie 1</span> <br><br>
<span class="pytanie">Do ktorej klasy chodzi lama?</span>
<input type="radio" name="radAns1" value="1" checked>Liceum
<input type="radio" name="radAns1" value="2">Gimbazjum
<input type="radio" name="radAns1" value="3">Podstawowka
<input type="radio" name="radAns1" value="4">Zawodowka
<input type="radio" name="radAns1" value="5">Technikum
</div><br><br>
<div id="pytanie 2" class="pytania">
<span class="pytanie-numer">Pytanie 2</span> <br><br>
<span class="pytanie">Jakiego radia slucha lama?</span>
<input type="radio" name="radAns2" value="1" checked>Radio Maryja
<input type="radio" name="radAns2" value="2">Radio Gold
<input type="radio" name="radAns2" value="3">Radio Kaszebe
<input type="radio" name="radAns2" value="4">Eska-Tv
<input type="radio" name="radAns2" value="5">Radio Z/Radio RMF-FM
</div><br><br>
<div id="pytanie 3" class="pytania">
<span class="pytanie-numer">Pytanie 3</span> <br><br>
<span class="pytanie">Z czego sklada sie dieta lamy?</span>
<input type="radio" name="radAns3" value="1" checked>Z marchwi
<input type="radio" name="radAns3" value="2">Z jablka
<input type="radio" name="radAns3" value="3">Z galazek
<input type="radio" name="radAns3" value="4">Z grzybow
<input type="radio" name="radAns3" value="5">Z siana
</div><br><br>
<div id="pytanie 4" class="pytania">
<span class="pytanie-numer">Pytanie 4</span> <br><br>
<span class="pytanie">Okresl skilla w CS'a lamy.</span>
<input type="radio" name="radAns4" value="1" checked>Noob
<input type="radio" name="radAns4" value="2">Silver
<input type="radio" name="radAns4" value="3">Lama
<input type="radio" name="radAns4" value="4">Ciota
<input type="radio" name="radAns4" value="5">Wszystkie odpowiedzi
</div><br><br>
<div id="pytanie 5" class="pytania">
<span class="pytanie-numer">Pytanie 5</span> <br><br>
<span class="pytanie">Czy lama jedzie autem/rowerem?</span>
<input type="radio" name="radAns5" value="1" checked>Nie bo, nie umie jezdzic
<input type="radio" name="radAns5" value="2">Nie, bo jest za glupi
<input type="radio" name="radAns5" value="3">Nie bo, ma kopyta
<input type="radio" name="radAns5" value="4">Nie bo, zostal skocony
<input type="radio" name="radAns5" value="5">Nie bo, jest debilem i wszyskie odpowiedzi powyzej
</div><br><br>
<input type="submit" value="Wyslij odpowiedzi">
</form>

Perhaps the Javascript code in the 'validateRadio' function can be easier:
// The html
<form onsubmit="validateSubmit(this);return false;" action='#'>
<div id="pytanie 1" class="pytania">
<span class="pytanie-numer">Pytanie 1</span> <br><br>
<span class="pytanie">Do ktorej klasy chodzi lama?</span>
<input type="radio" name="radAns1" value="1" checked>Liceum
<input type="radio" name="radAns1" value="2">Gimbazjum
<input type="radio" name="radAns1" value="3">Podstawowka
<input type="radio" name="radAns1" value="4">Zawodowka
<input type="radio" name="radAns1" value="5">Technikum
</div><br><br>
<div id="pytanie 2" class="pytania">
<span class="pytanie-numer">Pytanie 2</span> <br><br>
<span class="pytanie">Jakiego radia slucha lama?</span>
<input type="radio" name="radAns2" value="1" checked>Radio Maryja
<input type="radio" name="radAns2" value="2">Radio Gold
<input type="radio" name="radAns2" value="3">Radio Kaszebe
<input type="radio" name="radAns2" value="4">Eska-Tv
<input type="radio" name="radAns2" value="5">Radio Z/Radio RMF-FM
</div><br><br>
<div id="pytanie 3" class="pytania">
<span class="pytanie-numer">Pytanie 3</span> <br><br>
<span class="pytanie">Z czego sklada sie dieta lamy?</span>
<input type="radio" name="radAns3" value="1" checked>Z marchwi
<input type="radio" name="radAns3" value="2">Z jablka
<input type="radio" name="radAns3" value="3">Z galazek
<input type="radio" name="radAns3" value="4">Z grzybow
<input type="radio" name="radAns3" value="5">Z siana
</div><br><br>
<div id="pytanie 4" class="pytania">
<span class="pytanie-numer">Pytanie 4</span> <br><br>
<span class="pytanie">Okresl skilla w CS'a lamy.</span>
<input type="radio" name="radAns4" value="1" checked>Noob
<input type="radio" name="radAns4" value="2">Silver
<input type="radio" name="radAns4" value="3">Lama
<input type="radio" name="radAns4" value="4">Ciota
<input type="radio" name="radAns4" value="5">Wszystkie odpowiedzi
</div><br><br>
<div id="pytanie 5" class="pytania">
<span class="pytanie-numer">Pytanie 5</span> <br><br>
<span class="pytanie">Czy lama jedzie autem/rowerem?</span>
<input type="radio" name="radAns5" value="1" checked>Nie bo, nie umie jezdzic
<input type="radio" name="radAns5" value="2">Nie, bo jest za glupi
<input type="radio" name="radAns5" value="3">Nie bo, ma kopyta
<input type="radio" name="radAns5" value="4">Nie bo, zostal skocony
<input type="radio" name="radAns5" value="5">Nie bo, jest debilem i wszyskie odpowiedzi powyzej
</div><br><br>
<input type="submit" value="Wyslij odpowiedzi">
</form>
<div id="scoreMsg"></div>
// The Javascript
function validateRadio(obj, correct) {
return obj.value == correct;
}
function validateSubmit(obj) {
var score = 0;
var scoreMsg = document.getElementById('scoreMsg');
if (validateRadio(obj.radAns1, 2)) {
score += 1;
}
if (validateRadio(obj.radAns2, 1)) {
score += 1;
}
if (validateRadio(obj.radAns3, 3)) {
score += 1;
}
if (validateRadio(obj.radAns4, 5)) {
score += 1;
}
if (validateRadio(obj.radAns5, 4)) {
score += 1;
}
scoreMsg.innerHTML = score;
}

Related

How to remove disabled attribute from button if checked box is true?

I have a bunch of checkbox items. When I click the checkbox, I want the disabled attribute to be removed from the button, allowing the button to be clicked and a total displayed.
I've attached calcButton.removeAttribute('disabled'); to the conditional, but it's not removing the disabled attribute from the button.
var calcButton = document.getElementById("calcButton");
if (document.getElementById("total")) {
calcTotal();
}
function calcTotal() {
var itemTotal = 0;
var items = document.getElementsByTagName("input");
for (var i = 0; i < 11; i++) {
if (items[i].checked) {
itemTotal += items[i].value * 1;
calcButton.removeAttribute('disabled');
}
document.getElementById("total").innerHTML = "Your order total is: $" + itemTotal + ".00";
}
}
var payOptions = document.getElementById('payOpts');
if (calcButton.addEventListener) {
calcButton.addEventListener("click", calcTotal, false);
} else if (calcButton.attachEvent) {
calcButton.attachEvent("onclick", calcTotal);
}
calcButton.addEventListener('click', function() {
payOptions.style.display = 'block';
})
form {
display: flex;
flex-direction: column;
}
form label {
margin: 5px 0;
}
button {
width: fit-content;
}
<form>
<label for="item1" class="container">Hamburger ($5.00)
<input type="checkbox" id="item1" value="5">
<span class="checkmark"></span>
</label>
<label for="item2" class="container">Hotdog ($5.00)
<input type="checkbox" id="item2" value="5">
<span class="checkmark"></span>
</label>
<label for="item3" class="container">Jumbo Hotdog ($7.00)
<input type="checkbox" id="item3" value="7">
<span class="checkmark"></span>
</label>
<label for="item4" class="container">Corndog ($4.00)
<input type="checkbox" id="item4" value="4">
<span class="checkmark"></span>
</label>
<label for="item5" class="container">Chicken Fingers ($6.00)
<input type="checkbox" id="item5" value="5">
<span class="checkmark"></span>
</label>
<label for="item6" class="container">Nachos ($4.00)
<input type="checkbox" id="item6" value="4">
<span class="checkmark"></span>
</label>
<label for="item7" class="container">French Fries ($3.00)
<input type="checkbox" id="item7" value="3">
<span class="checkmark"></span>
</label>
<label for="item8" class="container">Soft Pretzel ($3.00)
<input type="checkbox" id="item8" value="3">
<span class="checkmark"></span>
</label>
<label for="item9" class="container">Small Drink ($2.00)
<input type="checkbox" id="item9" value="2">
<span class="checkmark"></span>
</label>
<label for="item10" class="container">Large Drink ($4.00)
<input type="checkbox" id="item10" value="4">
<span class="checkmark"></span>
</label>
<label for="item11" class="container">Bottled Water ($3.00)
<input type="checkbox" id="item11" value="3">
<span class="checkmark"></span>
</label>
<p id="total" class="priceInfo"></p>
<button type="button" id="calcButton" disabled="disabled">Pay me this!</button>
<div class="pay-options" id="payOpts" style="display: none;">
<h4>Hello World</h4>
</div>
</form>
You're attaching the onclick on the disabled calcButton, and that doesn't work as it's disabled and can't enabled itself.
calcTotal is also called at the beginning, but there aren't options selected so the calcbutton won't be enabled also
See this example. If have added another button to show that removeAttribute is working well:
var calcButton = document.getElementById("calcButton");
if (document.getElementById("total")) {
calcTotal();
}
function calcTotal() {
var itemTotal = 0;
var items = document.getElementsByTagName("input");
for (var i = 0; i < 11; i++) {
if (items[i].checked) {
itemTotal += items[i].value * 1;
calcButton.removeAttribute('disabled');
}
document.getElementById("total").innerHTML = "Your order total is: $" + itemTotal + ".00";
}
}
var payOptions = document.getElementById('payOpts');
if (calcButton.addEventListener) {
calcButton.addEventListener("click", calcTotal, false);
} else if (calcButton.attachEvent) {
calcButton.attachEvent("onclick", calcTotal);
}
document.getElementById("realCalcButton").addEventListener("click", calcTotal, false);
calcButton.addEventListener('click', function() {
payOptions.style.display = 'block';
})
form {
display: flex;
flex-direction: column;
}
form label {
margin: 5px 0;
}
button {
width: fit-content;
}
<form>
<label for="item1" class="container">Hamburger ($5.00)
<input type="checkbox" id="item1" value="5">
<span class="checkmark"></span>
</label>
<label for="item2" class="container">Hotdog ($5.00)
<input type="checkbox" id="item2" value="5">
<span class="checkmark"></span>
</label>
<label for="item3" class="container">Jumbo Hotdog ($7.00)
<input type="checkbox" id="item3" value="7">
<span class="checkmark"></span>
</label>
<label for="item4" class="container">Corndog ($4.00)
<input type="checkbox" id="item4" value="4">
<span class="checkmark"></span>
</label>
<label for="item5" class="container">Chicken Fingers ($6.00)
<input type="checkbox" id="item5" value="5">
<span class="checkmark"></span>
</label>
<label for="item6" class="container">Nachos ($4.00)
<input type="checkbox" id="item6" value="4">
<span class="checkmark"></span>
</label>
<label for="item7" class="container">French Fries ($3.00)
<input type="checkbox" id="item7" value="3">
<span class="checkmark"></span>
</label>
<label for="item8" class="container">Soft Pretzel ($3.00)
<input type="checkbox" id="item8" value="3">
<span class="checkmark"></span>
</label>
<label for="item9" class="container">Small Drink ($2.00)
<input type="checkbox" id="item9" value="2">
<span class="checkmark"></span>
</label>
<label for="item10" class="container">Large Drink ($4.00)
<input type="checkbox" id="item10" value="4">
<span class="checkmark"></span>
</label>
<label for="item11" class="container">Bottled Water ($3.00)
<input type="checkbox" id="item11" value="3">
<span class="checkmark"></span>
</label>
<p id="total" class="priceInfo"></p>
<button type="button" id="realCalcButton">Calculate</button>
<button type="button" id="calcButton" disabled="disabled">Pay me this!</button>
<div class="pay-options" id="payOpts" style="display: none;">
<h4>Hello World</h4>
</div>
</form>

How to auto check radio button basis of two radio button groups

<div class="product_colors">
<span class="header" style="display:block;">Color</span>
<label class="color_label active">
<input type="radio" name="product_color" value="gold" >Gold
<span style="""></span>
</label>
<label class="color_label">
<input type="radio" name="product_color" value="rose gold">Rose Gold
<span style="" data-title="rose gold"></span>
</label>
<label class="color_label">
<input type="radio" name="product_color" value="silver" > Silver
<span style="" data-title="silver"></span>
</label>
</div>
<div class="product_stones">
<span class="header" style="display:block;">Stone</span>
<label class="stone_label">
<input type="radio" name="product_stone" value="malachite" >malachite
</label>
<label class="stone_label active">
<input type="radio" name="product_stone" value="tiger-eye" > tiger-eye
</label>
<label class="stone_label">
<input type="radio" name="product_stone" value="black" > black
</label>
<label class="stone_label">
<input type="radio" name="product_stone" value="blue" > blue
</label>
</div>
<div class="combination">
Combination
<div class="hidden">
<input type="radio" name="combination" class="hidden_wrap" data-color="gold" data-stone="malachite" data-handle="joory-earring-malachite-gold"> gold-malachite
<input type="radio" name="combination" class="hidden_wrap" data-color="gold" data-stone="tiger-eye" data-handle="copy-of-joory-earrings-tiger-eye-gold">gold-tiger-eye
<input type="radio" name="combination" class="hidden_wrap" data-color="rose gold" data-stone="black" data-handle="kanz-ring-black-rose-gold"> rose-gold-black
<input type="radio" name="combination" class="hidden_wrap" data-color="silver" data-stone="blue" data-handle="joory-earring-blue-silver"> silver-blue
</div>
</div>
here is my output image
I want to change combination radio button value to be select automatically on the basis of selected color and stone. Can someone help me to get rid of this problem.
Here is my code I've tried everything but I am new in JS so I can't find solution of this problem
Color
Gold
Rose Gold
Silver
<div class="product_stones">
<span class="header" style="display:block;">Stone</span>
<label class="stone_label">
<input type="radio" name="product_stone" value="malachite" >malachite
</label>
<label class="stone_label active">
<input type="radio" name="product_stone" value="tiger-eye" > tiger-eye
</label>
<label class="stone_label">
<input type="radio" name="product_stone" value="black" > black
</label>
<label class="stone_label">
<input type="radio" name="product_stone" value="blue" > blue
</label>
</div>
<div class="combination">
Combination
<div class="hidden">
<input type="radio" name="combination" class="hidden_wrap" data-color="gold" data-stone="malachite" data-handle="joory-earring-malachite-gold"> gold-malachite
<input type="radio" name="combination" class="hidden_wrap" data-color="gold" data-stone="tiger-eye" data-handle="copy-of-joory-earrings-tiger-eye-gold">gold-tiger-eye
<input type="radio" name="combination" class="hidden_wrap" data-color="rose gold" data-stone="black" data-handle="kanz-ring-black-rose-gold"> rose-gold-black
<input type="radio" name="combination" class="hidden_wrap" data-color="silver" data-stone="blue" data-handle="joory-earring-blue-silver"> silver-blue
</div>
</div>
Here is another solution I've tried which is not edit HTML.
My solution is going to find combination radio button that has proper data-color and data-stone
$("input[name^='product_']").on('change', (e) => {
$("input[name='combination']").prop('checked', false);
var productColor = $("input[name='product_color']:checked").val();
var productStone = $("input[name='product_stone']:checked").val();
if (productColor !== undefined && productStone !== undefined) {
if ($(`input[data-color='${productColor}'][data-stone='${productStone}']`).length) {
$(`input[data-color='${productColor}'][data-stone='${productStone}']`).trigger('click');
}
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="product_colors">
<span class="header" style="display:block;">Color</span>
<label class="color_label active">
<input type="radio" name="product_color" value="gold" >Gold
<span style="""></span>
</label>
<label class="color_label">
<input type="radio" name="product_color" value="rose gold">Rose Gold
<span style="" data-title="rose gold"></span>
</label>
<label class="color_label">
<input type="radio" name="product_color" value="silver" > Silver
<span style="" data-title="silver"></span>
</label>
</div>
<div class="product_stones">
<span class="header" style="display:block;">Stone</span>
<label class="stone_label">
<input type="radio" name="product_stone" value="malachite" >malachite
</label>
<label class="stone_label active">
<input type="radio" name="product_stone" value="tiger-eye" > tiger-eye
</label>
<label class="stone_label">
<input type="radio" name="product_stone" value="black" > black
</label>
<label class="stone_label">
<input type="radio" name="product_stone" value="blue" > blue
</label>
</div>
<div class="combination">
Combination
<div class="hidden">
<input type="radio" name="combination" class="hidden_wrap" data-color="gold" data-stone="malachite" data-handle="joory-earring-malachite-gold"> gold-malachite
<input type="radio" name="combination" class="hidden_wrap" data-color="gold" data-stone="tiger-eye" data-handle="copy-of-joory-earrings-tiger-eye-gold">gold-tiger-eye
<input type="radio" name="combination" class="hidden_wrap" data-color="rose gold" data-stone="black" data-handle="kanz-ring-black-rose-gold"> rose-gold-black
<input type="radio" name="combination" class="hidden_wrap" data-color="silver" data-stone="blue" data-handle="joory-earring-blue-silver"> silver-blue
</div>
</div>
You need some jQuery to achieve this
<script>
$(document).ready(function() {
$('.product_description').click(function() {
var color = $('input[name="product_color"]:checked').val();
var stone = $('input[name="product_stone"]:checked').val();
var combinationClass = color + "-" + stone
if ($('.' + combinationClass).length) {
$('.' + combinationClass).attr('checked', true)
} else {
//If the class name of the combination is not found
alert("something went wrong");
}
});
});
</script>
HTML Code
<!--
# Added common class for all the stone and colour radio buttons to enable trigger
# Added Class based on the colour and stone value in the combination
# Added checked attribute to stone and colour radio buttons for on Load default selection
-->
<div class="product_colors">
<span class="header" style="display:block;">Color</span>
<label class="color_label">
<input type="radio" class="product_description" name="product_color" value="gold" checked>Gold
<span></span>
</label>
<label class="color_label">
<input type="radio" class="product_description" name="product_color" value="rose-gold">Rose Gold
<span data-title="rose gold"></span>
</label>
<label class="color_label">
<input type="radio" class="product_description" name="product_color" value="silver"> Silver
<span data-title="silver"></span>
</label>
</div>
<div class="product_stones">
<span class="header" style="display:block;">Stone</span>
<label class="stone_label">
<input type="radio" class="product_description" name="product_stone" value="malachite" checked>malachite
</label>
<label class="stone_label active">
<input type="radio" class="product_description" name="product_stone" value="tiger-eye"> tiger-eye
</label>
<label class="stone_label">
<input type="radio" class="product_description" name="product_stone" value="black"> black
</label>
<label class="stone_label">
<input type="radio" class="product_description" name="product_stone" value="blue"> blue
</label>
</div>
<div class="combination">
Combination
<div class="hidden">
<input type="radio" name="combination" class="hidden_wrap gold-malachite" data-color="gold" data-stone="malachite" data-handle="joory-earring-malachite-gold"> gold-malachite
<input type="radio" name="combination" class="hidden_wrap gold-toger-eye" data-color="gold" data-stone="tiger-eye" data-handle="copy-of-joory-earrings-tiger-eye-gold">gold-tiger-eye
<input type="radio" name="combination" class="hidden_wrap rose-gold-black" data-color="rose gold" data-stone="black" data-handle="kanz-ring-black-rose-gold"> rose-gold-black
<input type="radio" name="combination" class="hidden_wrap silver-blue" data-color="silver" data-stone="blue" data-handle="joory-earring-blue-silver"> silver-blue
</div>
</div>

Why is my counter always equal to zero even after the correct radio button is pressed?

In my Javascript code, I increment the counter when the right radio button is checked but when I check in the console, the counter doesn't get updated after the correct radio button is checked. Even after I click the submit button which calls a function clicked() that displays the counter. The counter still remains zero. Is there a reason why it doesn't get updated. Here is my Java Script code:
var counter = 0;
if (document.getElementById('blue').checked) {
counter++;
}
if (document.getElementById('age3').checked) {
counter++;
}
if (document.getElementById('hobby2').checked) {
counter++;
}
if (document.getElementById('game3').checked) {
counter++;
}
if (document.getElementById('language4').checked) {
counter++;
}
function clicked() {
document.getElementById("result").innerHTML = "You got " + counter;
}
<h1>Quiz</h1>
<form>
<p>(1) What is my favourite Color?</p>
<input type="radio" id="blue" name="color" value="blue">
<label for="blue">blue</label><br>
<input type="radio" id="red" name="color" value="red">
<label for="red">red</label><br>
<input type="radio" id="green" name="color" value="green">
<label for="green">green</label><br>
<input type="radio" id="purple" name="color" value="purple">
<label for="purple">purple</label>
<br>
<p>(2) How Old am I?</p>
<input type="radio" id="age1" name="age" value="20">
<label for="age1">20</label><br>
<input type="radio" id="age2" name="age" value="22">
<label for="age2">22</label><br>
<input type="radio" id="age3" name="age" value="21">
<label for="age3">21</label><br>
<input type="radio" id="age4" name="age" value="23">
<label for="age4">23</label>
<br>
<p>(3) Which of the following is not of a hobby of mine?</p>
<input type="radio" id="hobby1" name="hobby" value="swimming">
<label for="hobby1">swimming</label><br>
<input type="radio" id="hobby2" name="hobby" value="soccer">
<label for="hobby2">soccer</label><br>
<input type="radio" id="hobby3" name="hobby" value="chess">
<label for="hobby3">chess</label><br>
<input type="radio" id="hobby4" name="hobby" value="coding">
<label for="hobby4">coding</label>
<br>
<p>(4) Which of the following is a game that I like?</p>
<input type="radio" id="game1" name="game" value="NBA">
<label for="game1">NBA</label><br>
<input type="radio" id="game2" name="game" value="FortNite">
<label for="game2">FortNite</label><br>
<input type="radio" id="game3" name="game" value="God of War">
<label for="game3">God of War</label><br>
<input type="radio" id="game4" name="game" value="Call of Duty">
<label for="game4">Call of Duty</label>
<p>(5) At what is my favourite language</p>
<input type="radio" id="language1" name="language" value="python">
<label for="language1">python</label><br>
<input type="radio" id="language2" name="language" value="Javascript">
<label for="language2">Javascript</label><br>
<input type="radio" id="language3" name="language" value="C++">
<label for="language3">C++</label><br>
<input type="radio" id="language4" name="language" value="Java">
<label for="language4">Java</label><br><br>
</form>
<button onclick="clicked()">Submit</button>
<p id="result"> </p>
Put all those radio button checkings into a function and call that function when you hit submit. This should solve your problem.
var counter = 0;
function updateCounter(){
if (document.getElementById('blue').checked) {
counter++;
}
if (document.getElementById('age3').checked) {
counter++;
}
if (document.getElementById('hobby2').checked) {
counter++;
}
if (document.getElementById('game3').checked) {
counter++;
}
if (document.getElementById('language4').checked) {
counter++;
}
}
function clicked() {
updateCounter()
document.getElementById("result").innerHTML = "You got " + counter;
//reset the counter back to zero after displaying score
counter = 0
}
<h1>Quiz</h1>
<form>
<p>(1) What is my favourite Color?</p>
<input type="radio" id="blue" name="color" value="blue">
<label for="blue">blue</label><br>
<input type="radio" id="red" name="color" value="red">
<label for="red">red</label><br>
<input type="radio" id="green" name="color" value="green">
<label for="green">green</label><br>
<input type="radio" id="purple" name="color" value="purple">
<label for="purple">purple</label>
<br>
<p>(2) How Old am I?</p>
<input type="radio" id="age1" name="age" value="20">
<label for="age1">20</label><br>
<input type="radio" id="age2" name="age" value="22">
<label for="age2">22</label><br>
<input type="radio" id="age3" name="age" value="21">
<label for="age3">21</label><br>
<input type="radio" id="age4" name="age" value="23">
<label for="age4">23</label>
<br>
<p>(3) Which of the following is not of a hobby of mine?</p>
<input type="radio" id="hobby1" name="hobby" value="swimming">
<label for="hobby1">swimming</label><br>
<input type="radio" id="hobby2" name="hobby" value="soccer">
<label for="hobby2">soccer</label><br>
<input type="radio" id="hobby3" name="hobby" value="chess">
<label for="hobby3">chess</label><br>
<input type="radio" id="hobby4" name="hobby" value="coding">
<label for="hobby4">coding</label>
<br>
<p>(4) Which of the following is a game that I like?</p>
<input type="radio" id="game1" name="game" value="NBA">
<label for="game1">NBA</label><br>
<input type="radio" id="game2" name="game" value="FortNite">
<label for="game2">FortNite</label><br>
<input type="radio" id="game3" name="game" value="God of War">
<label for="game3">God of War</label><br>
<input type="radio" id="game4" name="game" value="Call of Duty">
<label for="game4">Call of Duty</label>
<p>(5) At what is my favourite language</p>
<input type="radio" id="language1" name="language" value="python">
<label for="language1">python</label><br>
<input type="radio" id="language2" name="language" value="Javascript">
<label for="language2">Javascript</label><br>
<input type="radio" id="language3" name="language" value="C++">
<label for="language3">C++</label><br>
<input type="radio" id="language4" name="language" value="Java">
<label for="language4">Java</label><br><br>
</form>
<button onclick="clicked()">Submit</button>
<p id="result"> </p>
Every time you are getting the value as 0 as the login you written is not calling on clicking of radio button.
First thing Just defined the all radio button into a method like below.
function SelectValue () {
counter = 0;
if (document.getElementById('blue').checked)
{
counter++;
}
if (document.getElementById('age3').checked)
{
counter++;
}
if (document.getElementById('hobby2').checked)
{
counter++;
}
if (document.getElementById('game3').checked)
{
counter++;
}
if (document.getElementById('language4').checked)
{
counter++;
}
}
Now there is two way you can call.
Either call that method in each and every method like below.
<p>(1) What is my favourite Color?</p>
<input type="radio" id="blue" name="color" value="blue" onclick="clickmethodthod()">
<label for="blue">blue</label><br>
Write a logic of click and attached to all radio button.
let counter = 0;
const radios = document.querySelector('input[type="radio"]');
for(radio in radios) {
radios[radio].onclick = function() {
SelectValue ()
}
}
Let me know if you are getting any issue.

Retain Multiple Radio Buttons checked after page refresh

In a form there are 2 group of radio buttons.
In the first group named Result, there are 4 option: id="ok", id="fa", id="fp", id="bp".
In the second group named ResultCategories, there are 9 option: id="cat1" .... id="cat9".
What I want:
a. If ok is clicked, ResultCategories will be unchecked (if already checked).
b. If fp or bp is clicked, cat9 of ResultCategories will be checked.
c. If one of the cat1 to cat8 of ResultCategories is clicked, fa of Result will be checked.
d. When radio buttons are clicked page will refresh and checked radio buttons remain checked.
I got a to c working but d is not working. It retains checked radio for only one group.
Here is what tried:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
</head>
<body>
<div class="container">
<form action="" method="POST">
<fieldset class="scheduler-border">
<legend class="scheduler-border">Quality Check</legend>
<div style="float: right;">
<button type="submit" id="submit" name="submit" class="btn btn-info">Complete</button>
</div>
<br />
<br />
<br />
<div class="row">
<div class="column">
<div id="Result">
<label>Result:</label>
<label class="radioContainer">Ok
<input type="radio" name="Result" id ="ok" value="1" />
<span class="circle"></span>
</label>
<label class="radioContainer">Fasle Alarm
<input type="radio" name="Result" id="fa" value="2" />
<span class="circle"></span>
</label>
<label class="radioContainer">False Pass
<input type="radio" name="Result" id="fp" value="3" />
<span class="circle"></span>
</label>
<label class="radioContainer">Blatant Pass
<input type="radio" name="Result" id="bp" value="4" />
<span class="circle"></span>
</label>
</div>
</div>
<br />
<div class="column">
<div id="ResultCategories">
<label>Result Categories:</label>
<div>
<label class="radioContainer">Cat 1
<input type="radio" name="ResultCategories" id="cat1" value="1" />
<span class="circle"></span>
</label>
<label class="radioContainer">Cat 2
<input type="radio" name="ResultCategories" id="cat2" value="2" />
<span class="circle"></span>
</label>
<label class="radioContainer">Cat 3
<input type="radio" name="ResultCategories" id="cat3" value="3" />
<span class="circle"></span>
</label>
<label class="radioContainer">Cat 4
<input type="radio" name="ResultCategories" id="cat4" value="4" />
<span class="circle"></span>
</label>
<label class="radioContainer">Cat 5
<input type="radio" name="ResultCategories" id="cat5" value="5" />
<span class="circle"></span>
</label>
<label class="radioContainer">Cat 6
<input type="radio" name="ResultCategories" id="cat6" value="6" />
<span class="circle"></span>
</label>
<label class="radioContainer">Cat 7
<input type="radio" name="ResultCategories" id="cat7" value="7" />
<span class="circle"></span>
</label>
<label class="radioContainer">Cat 8
<input type="radio" name="ResultCategories" id="cat8" value="8" />
<span class="circle"></span>
</label>
<label class="radioContainer">Cat 9
<input type="radio" name="ResultCategories" id="cat9" value="9" />
<span class="circle"></span>
</label>
</div>
</div>
</div>
</div>
</fieldset>
</form>
</div>
</body>
<script> $('input:radio').click(function() {
location.reload(); }); </script>
I have added a fiddle here: Fiddle
$(document).ready(function() {
var result_dom = $('input[name="Result"]');
var categories_dom = $('input[name="ResultCategories"]');
var cat9 = $('#cat9');
var fa = $('#fa')
result_dom.on('change', function() {
var checked_val = $(this).val();
if (checked_val == 1) {
categories_dom.prop('checked', false);
} else if (checked_val == 3 || checked_val == 4) {
cat9.prop('checked', true);
}
});
categories_dom.on('change', function() {
var checked_val = $(this).val();
if (checked_val >= 1 && checked_val <= 8) {
fa.prop('checked', true);
}
});
});
$(document).ready(function(){
if(localStorage.selected) {
$('#' + localStorage.selected ).attr('checked', true);
}
$('.radio').click(function(){
localStorage.setItem("selected", this.id);
});
});
How can I retain both group of radio buttons checked?
Updated Code:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
var result_dom = $('input[name="Result"]');
var categories_dom = $('input[name="ResultCategories"]');
var cat9 = $('#cat9');
var fa = $('#fa')
result_dom.on('change', function() {
var checked_val = $(this).val();
if (checked_val == 1) {
categories_dom.prop('checked', false);
} else if (checked_val == 3 || checked_val == 4) {
cat9.prop('checked', true);
}
});
categories_dom.on('change', function() {
var checked_val = $(this).val();
if (checked_val >= 1 && checked_val <= 8) {
fa.prop('checked', true);
}
});
});$(document).ready(function() {
var result_dom = $('input[name="Result"]');
var categories_dom = $('input[name="ResultCategories"]');
var cat9 = $('#cat9');
var fa = $('#fa')
result_dom.on('change', function() {
var checked_val = $(this).val();
if (checked_val == 1) {
categories_dom.prop('checked', false);
} else if (checked_val == 3 || checked_val == 4) {
cat9.prop('checked', true);
}
});
categories_dom.on('change', function() {
var checked_val = $(this).val();
if (checked_val >= 1 && checked_val <= 8) {
fa.prop('checked', true);
}
});
});
$(document).ready(function(){
//get the selected radios from storage, or create a new empty object
var radioGroups = JSON.parse(localStorage.getItem('selected') || '{}');
//loop over the ids we previously selected and select them again
Object.values(radioGroups).forEach(function(radioId){
document.getElementById(radioId).checked = true;
});
//handle the click of each radio
$('.radio').on('click', function(){
//set the id in the object based on the radio group name
//the name lets us segregate the values and easily replace
//previously selected radios in the same group
radioGroups[this.name] = this.id;
//finally store the updated object in storage for later use
localStorage.setItem("selected", JSON.stringify(radioGroups));
});
});
</script>
</head>
<body>
<div class="container">
<form action="" method="POST">
<fieldset class="scheduler-border">
<legend class="scheduler-border">Quality Check</legend>
<div style="float: right;"><button type="submit" id="submit" name="submit" class="btn btn-info">Complete</button></div>
<br /> <br /> <br />
<div class="row">
<div class="column">
<div id="Result">
<label>Result:</label>
<label class="radioContainer">Ok
<input class="radio" type="radio" name="Result" id ="ok" value="1">
<span class="circle"></span>
</label>
<label class="radioContainer">Fasle Alarm <input class="radio" type="radio" name="Result" id="fa" value="2">
<span class="circle"></span>
</label>
<label class="radioContainer">False Pass <input class="radio" type="radio" name="Result" id="fp" value="3" >
<span class="circle"></span>
</label>
<label class="radioContainer">Blatant Pass <input class="radio" type="radio" name="Result" id="bp" value="4">
<span class="circle"></span>
</label>
</div>
</div>
<br />
<div class="column">
<div id="ResultCategories"><label>Result Categories:</label>
<div>
<label class="radioContainer">Cat 1 <input class="radio" type="radio" name="ResultCategories" id="cat1" value="1">
<span class="circle"></span>
</label>
<label class="radioContainer">Cat 2 <input class="radio" type="radio" name="ResultCategories" id="cat2" value="2">
<span class="circle"></span>
</label>
<label class="radioContainer">Cat 3 <input class="radio" type="radio" name="ResultCategories" id="cat3" value="3">
<span class="circle"></span>
</label>
<label class="radioContainer">Cat 4 <input class="radio" type="radio" name="ResultCategories" id="cat4" value="4">
<span class="circle"></span>
</label>
<label class="radioContainer">Cat 5 <input class="radio" type="radio" name="ResultCategories" id="cat5" value="5">
<span class="circle"></span>
</label> <label class="radioContainer">Cat 6 <input class="radio" type="radio" name="ResultCategories" id="cat6" value="6">
<span class="circle"></span>
</label>
<label class="radioContainer">Cat 7 <input class="radio" type="radio" name="ResultCategories" id="cat7" value="7">
<span class="circle"></span>
</label> <label class="radioContainer">Cat 8 <input class="radio" type="radio" name="ResultCategories" id="cat8" value="8">
<span class="circle"></span>
</label>
<label class="radioContainer">Cat 9 <input class="radio" type="radio" name="ResultCategories" id="cat9" value="9">
<span class="circle"></span>
</label>
</div>
</div>
</div>
</div>
</fieldset>
</form>
</div>
</body>
<script>
$('input:radio').click(function() {
location.reload();
});
</script>
$(document).ready(function(){
//get the selected radios from storage, or create a new empty object
var radioGroups = JSON.parse(localStorage.getItem('selected') || '{}');
//loop over the ids we previously selected and select them again
Object.values(radioGroups).forEach(function(radioId){
document.getElementById(radioId).checked = true;
});
//handle the click of each radio
$('.radio').on('click', function(){
//set the id in the object based on the radio group name
//the name lets us segregate the values and easily replace
//previously selected radios in the same group
radioGroups[this.name] = this.id;
//finally store the updated object in storage for later use
localStorage.setItem("selected", JSON.stringify(radioGroups));
});
});

The function does not work when i press submit with empty form

Here is my HTML Code :
<form name="myForm" action="userreview.html" onsubmit="return !!(tosubmit() & validateForm())" >
<div style="padding-bottom: 18px;">First Name:<span style="color: red;"> </span><br/></div>
<input type="text" name="firstname" id="firstname">
<br>
<div style="padding-bottom: 18px;">Last Name:<span style="color: red;"> </span><br/></div>
<input type="text" name="lastname" id="lastname">
<br>
<div style="padding-bottom: 18px;">Review:<span style="color: red;"> </span><br/></div>
<textarea id="data_8" ${readonly} name="data_8" style="width : 450px;" rows="10" class="form-control"></textarea>
<nav>
<fieldset class="rating" name="rate1">
<legend>Please rate:</legend>
<input type="radio" id="star5" name="rating" value="5" onchange="test(this)" /><label for="star5" title="Rocks!">★</label>
<input type="radio" id="star4" name="rating" value="4" onchange="test(this)" /><label for="star4" title="Pretty good">★</label>
<input type="radio" id="star3" name="rating" value="3" onchange="test(this)" /><label for="star3" title="Meh">★</label>
<input type="radio" id="star2" name="rating" value="2" onchange="test(this)" /><label for="star2" title="Kinda bad">★</label>
<input type="radio" id="star1" name="rating" value="1" onchange="test(this)" /><label for="star1" title="Sucks big time">★</label>
</fieldset>
</nav>
<div style="padding-bottom: 18px;">Would you recommend this product?<span style="color: red;"> *</span><br/>
<span><input type="radio" id="data_9_0" name="data_9" value="Yes"/> Yes</span><br/>
<span><input type="radio" id="data_9_1" name="data_9" value="No"/> No</span><br/>
<span><input type="radio" id="data_9_2" name="data_9" value="I am not sure"/> I am not sure</span><br/>
</br>
<input type="submit" value="Submit">
</div>
</form>
</div>
Here is my jQuery Code :
<script>
function tosubmit() {
// Getting the value of your text input
var mytext = document.getElementById("data_8").value;
// Storing the value above into localStorage
localStorage.setItem("mytext", mytext);
localStorage.setItem("stars", stars);
return true;
}
var stars;
function test(myInput)
{
stars = myInput.value;
//alert(stars);
}
function validateForm() {
var x = document.querySelectorAll("#data_8, #rating, #firstname, #lastname");
if (x == "") {
alert("Name must be filled out");
return false;
}
}
</script>
How come it does not alert when I press submit with empty form? Did I make any mistake? Although it does not go to the other page but it does not alert the user to fill in the empty form.
Can someone help me? I been doing for quite long.
You can do smothing like this:
function empty() {
var x;
x = document.getElementById("YourInputId").value;
if (x == "") {
alert("Show an Alert");
return false;
};
}
return true;
and
<input type="submit" value="submit" onClick="return empty()" />
change your html code to something be like this
<form name="myForm" action="userreview.html" onclick="return formX()" />
and your JS function to
function formX(){
var xid;
xid= document.getElementById("id of html element").value;
if(xid=="") {
alert("This is empty data alert");
return false;
};
return true;
}
This will make sure not to submit empty data, & will alert user.
There are some inaccuracies in your code. Assuming that you want to validate all the fields, check this out:
var el = document.getElementById("myForm"),
stars = document.querySelectorAll("input[name='rating']"),
recommendations = document.querySelectorAll("input[name='data_9']");
el.addEventListener("submit", onSubmit, false);
for(var i = 0; i < stars.length; i++) stars[i].addEventListener('click', testStars, false);
for(var i = 0; i < recommendations.length; i++) recommendations[i].addEventListener('click', testRecommendations, false);
function onSubmit(event) {
var e = event || window.event
if(!(savetoStorage() && validateForm())) e.preventDefault();
}
function savetoStorage() {
var mytext = document.getElementById("data_8").value;
if(!star || !recommendation || mytext.trim() === '') return false;
localStorage.setItem("mytext", mytext);
localStorage.setItem("stars", stars);
return true;
}
var star = 0, recommendation = false;
function testStars() {
star = this.value;
}
function testRecommendations() {
recommendation = this.value;
}
function validateForm() {
var x = document.querySelectorAll("#data_8, #firstname, #lastname");
for(var i = 0; i < x.length; i++) if(!x[i].value || x[i].value.trim() === '') return false;
return true;
}
<form id="myForm" name="myForm" action="userreview.html">
<div style="padding-bottom: 18px;">First Name:<span style="color: red;"> </span><br/></div>
<input type="text" name="firstname" id="firstname">
<br>
<div style="padding-bottom: 18px;">Last Name:<span style="color: red;"> </span><br/></div>
<input type="text" name="lastname" id="lastname">
<br>
<div style="padding-bottom: 18px;">Review:<span style="color: red;"> </span><br/></div>
<textarea id="data_8" ${readonly} name="data_8" style="width : 450px;" rows="10" class="form-control"></textarea>
<nav>
<fieldset class="rating" name="rate1">
<legend>Please rate:</legend>
<input type="radio" id="star5" name="rating" value="5" /><label for="star5" title="Rocks!">★</label>
<input type="radio" id="star4" name="rating" value="4" /><label for="star4" title="Pretty good">★</label>
<input type="radio" id="star3" name="rating" value="3" /><label for="star3" title="Meh">★</label>
<input type="radio" id="star2" name="rating" value="2" /><label for="star2" title="Kinda bad">★</label>
<input type="radio" id="star1" name="rating" value="1" onchange="test(this)" /><label for="star1" title="Sucks big time">★</label>
</fieldset>
</nav>
<div style="padding-bottom: 18px;">Would you recommend this product?<span style="color: red;"> *</span><br/>
<span><input type="radio" id="data_9_0" name="data_9" value="Yes"/> Yes</span><br/>
<span><input type="radio" id="data_9_1" name="data_9" value="No"/> No</span><br/>
<span><input type="radio" id="data_9_2" name="data_9" value="I am not sure"/> I am not sure</span><br/>
</br>
<input type="submit" value="Submit">
</div>
</form>
Also notice that you will have to work on crossbrowserness if you want to stick to Vanilla. Or just use Jquery for events' handlers assignment, selecting elements and so on.

Categories

Resources