decrease progress bar on radio input value click - javascript

I have 2 separate code in one audit.php file and trying to combine it to decrease progress bar by the value of click on radio input I just can't put the logic together The calculation should be (var total/$auditno * 100/100)
Variable
$auditno = "20";
Function for decrease progress bar, this is where calculation (var total/$auditno * 100/100) should replace value=v1-10
function decrease() {
var v1=document.getElementById('p1').value;
document.getElementById("p1").value= v1 - 10;
}
Function to calculate value of click radio input
function setRadios() {
function sumRadios() {
var total = 0, i = 1, oForm = this.form;
while (radgrp = oForm.elements['Set' + (i++)])
{
j = radgrp.length;
do
if (radgrp[--j].checked)
{
total += Number(radgrp[j].value);
break;
}
while (j);
}
oForm.elements.total.value = total.toFixed(2);
}
var i = 0, input, inputs = document.getElementById('myemailform').getElementsByTagName('input');
while (input = inputs.item(i++))
if (input.name.match(/^Set\d+$/))
input.onclick = sumRadios;
}
onload = setRadios;
and Html
<div id="wrapper">
<form id="myemailform">
<fieldset class="audit">
<legend>Set 1</legend>
<input id="r1" type="radio" name="Set1" value="0" /><label for="r1">0</label><br />
<input id="r2" type="radio" name="Set1" value="1" /><label for="r2">1</label><br />
<input id="r3" type="radio" name="Set1" value="2" /><label for="r3">2</label>
</fieldset>
<fieldset class="audit">
<legend>Set 2</legend>
<input id="r4" type="radio" name="Set2" value="0" /><label for="r4">0</label><br />
<input id="r5" type="radio" name="Set2" value="1" /><label for="r5">1</label><br />
<input id="r6" type="radio" name="Set2" value="2" /><label for="r6">2</label>
</fieldset>
<fieldset class="audit">
<legend>Set 3</legend>
<input id="r7" type="radio" name="Set3" value="0" /><label for="r7">0</label><br />
<input id="r8" type="radio" name="Set3" value="1" /><label for="r8">1</label><br />
<input id="r9" type="radio" name="Set3" value="2" /><label for="r9">2</label>
</fieldset>
<fieldset style="position:relative;top:36px;width:140px;">
<input id="total" type="text" name="total" value="" /><strong> total</strong>
<input type="reset" style="font-size:11px;" />
</fieldset>
</form>
</div><br><br>
<progress value="100" max="100" id=p1>100%</progress>
<input type=button value='Decrease' onClick='decrease();'>

Related

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.

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.

Javascript - Calculating Sum of Checkboxes From Array

Based on the answers below I have edited the post to give some more details. Thanks everyone.
EDITED:
This is the code I have:
#foreach($amount_data as $amount)
<div class="col-sm-12">
<div class="input-checkbox">
<div class="inner"></div>
<input type="checkbox" name="items[]" value="{{$amount->amount}}" onchange="checkTotal()" />
</div>
<span>{{$amount->item_name}} - <b>{{$amount->amount}} {{$form->currency}}</b></span>
</div>
#endforeach
<br/> Total: <input type="text" size="2" name="total" value="0" />
#endif
Javascript:
<script type="text/javascript">
function checkTotal() {
var sum = 0,
frm = document.getElementById("payment-form"),
cbs = frm["items[]"],
i;
for (i = 0; i < cbs.length; i++) {
if (cbs[i].checked) {
sum += parseInt(cbs[i].value);
}
}
frm.total.value = sum;
}
</script>
Form info:
<form action="{{url('secure-checkout/'.$form->unique_url_code)}}" method="POST" id="payment-form" name="payment-form">
Doesn't seem to work. No errors in console. Anything wrong?
You would need to use bracket notation because of the [] in the name
document.listForm["items[]"][i].checked
function checkTotal() {
var sum = 0,
frm = document.getElementById("payment-form"),
cbs = frm["items[]"],
i;
for (i = 0; i < cbs.length; i++) {
if (cbs[i].checked) {
sum += parseInt(cbs[i].value);
}
}
frm.total.value = sum;
}
<form name="payment-form" id="payment-form">
<input type="checkbox" name="items[]" value="2" onchange="checkTotal()" />2<br/>
<input type="checkbox" name="items[]" value="5" onchange="checkTotal()" />5<br/>
<input type="checkbox" name="items[]" value="10" onchange="checkTotal()" />10<br/>
<input type="checkbox" name="items[]" value="20" onchange="checkTotal()" />20<br/>
Total: <input type="text" size="2" name="total" value="0" />
</form>
Here is an answer using jQuery. Hope this helps a bit! I've separated the listener and the function as I believe it makes things easier to edit later on. You could combine them to shorten the code.
//Listener for the checkbox
$("input[name='choice']").change(function() {
sumUp();
});
//Funtion that adds the total up
function sumUp() {
var sum = 0;
$(" input[name='choice']:checked").each(function() {
sum += parseInt($(this).val());
});
$("input[name=total]").val(sum);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form name="listForm">
<input type="checkbox" name="choice" value="2" />2
<br/>
<input type="checkbox" name="choice" value="5" />5
<br/>
<input type="checkbox" name="choice" value="10" />10
<br/>
<input type="checkbox" name="choice" value="20" />20
<br/> Total:
<input type="text" size="2" name="total" value="0" />
</form>
You can get the Sum of checked checkboxes array by simply using Array.prototype.reduce():
function checkTotal() {
document.listForm.total.value = Array.prototype.reduce.call(
document.listForm.choice,
function (sum, el) {
return el.checked ? sum + +el.value : sum;
}, 0
);
}
<form name="listForm">
<input type="checkbox" name="choice" value="2" onchange="checkTotal()"/>2<br/>
<input type="checkbox" name="choice" value="5" onchange="checkTotal()"/>5<br/>
<input type="checkbox" name="choice" value="10" onchange="checkTotal()"/>10<br/>
<input type="checkbox" name="choice" value="20" onchange="checkTotal()"/>20<br/>
Total: <input type="text" size="2" name="total" value="0"/>
</form>

Calculate total on checkbox checked

HTML
<div id="catlist">
<input type="checkbox" id="cat_1" value="cat_1" price="1.5" /><label for="cat_1">cat_1</label><br/>
<input type="checkbox" id="cat_2" value="cat_2" price="2" /><label for="cat_2">cat_2</label><br/>
<input type="checkbox" id="cat_3" value="cat_3" price="3.5" /><label for="cat_3">cat_3</label><br/>
<input type="checkbox" id="cat_4" value="cat_4" price="4" /><label for="cat_4">cat_4</label><br/>
<input type="checkbox" id="cat_5" value="cat_5" price="5" /><label for="cat_5">cat_5</label><br/>
<input type="checkbox" id="cat_6" value="cat_6" price="6.5" /><label for="cat_6">cat_6</label><br/>
<input type="checkbox" id="cat_7" value="cat_7" price="7" /><label for="cat_7">cat_7</label><br/>
<input type="checkbox" id="cat_8" value="cat_8" price="8" /><label for="cat_8">cat_8</label><br/>
<input type="checkbox" id="cat_9" value="cat_9" price="9.5" /><label for="cat_9">cat_9</label>
</div>
<input type="text" id="total" value="0" />
Javascript
function calcAndShowTotal(){
var total = 0;
$('#catlist :checkbox[checked]').each(function(){
total =+ parseFloat($(this).attr('price')) || 0;
});
$('#total').val(total);
}
$('#pricelist :checkbox').click(function(){
calcAndShowTotal();
});
calcAndShowTotal();
I am getting particular value. WHY? I tried sum of total, i tried jquery but no success..
Use $('#catlist :checkbox:checked') selector to select checked check-boxes
[] is used as attribute selector and it could be used as '[type="checkbox"]' but it will not filter checked check-boxes
+ operator is not needed before parseFloat, it has to be total =+
Instead of calling handler, just invoke change handler using .change()
function calcAndShowTotal() {
var total = 0;
$('#catlist :checkbox:checked').each(function() {
total += parseFloat($(this).attr('price')) || 0;
});
$('#total').val(total);
}
$('#catlist :checkbox').change(calcAndShowTotal).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="catlist">
<input type="checkbox" id="cat_1" value="cat_1" price="1.5" />
<label for="cat_1">cat_1</label>
<br/>
<input type="checkbox" id="cat_2" value="cat_2" price="2" />
<label for="cat_2">cat_2</label>
<br/>
<input type="checkbox" id="cat_3" value="cat_3" price="3.5" />
<label for="cat_3">cat_3</label>
<br/>
<input type="checkbox" id="cat_4" value="cat_4" price="4" />
<label for="cat_4">cat_4</label>
<br/>
<input type="checkbox" id="cat_5" value="cat_5" price="5" />
<label for="cat_5">cat_5</label>
<br/>
<input type="checkbox" id="cat_6" value="cat_6" price="6.5" />
<label for="cat_6">cat_6</label>
<br/>
<input type="checkbox" id="cat_7" value="cat_7" price="7" />
<label for="cat_7">cat_7</label>
<br/>
<input type="checkbox" id="cat_8" value="cat_8" price="8" />
<label for="cat_8">cat_8</label>
<br/>
<input type="checkbox" id="cat_9" value="cat_9" price="9.5" />
<label for="cat_9">cat_9</label>
</div>
<input type="text" id="total" value="0" />
Using Array#reduce
function calcAndShowTotal() {
var total = [].reduce.call($('#catlist :checkbox:checked'), function(a, b) {
return a + +$(b).attr('price') || 0;
}, 0);
$('#total').val(total);
}
$('#catlist :checkbox').change(calcAndShowTotal).change();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="catlist">
<input type="checkbox" id="cat_1" value="cat_1" price="1.5" />
<label for="cat_1">cat_1</label>
<br/>
<input type="checkbox" id="cat_2" value="cat_2" price="2" />
<label for="cat_2">cat_2</label>
<br/>
<input type="checkbox" id="cat_3" value="cat_3" price="3.5" />
<label for="cat_3">cat_3</label>
<br/>
<input type="checkbox" id="cat_4" value="cat_4" price="4" />
<label for="cat_4">cat_4</label>
<br/>
<input type="checkbox" id="cat_5" value="cat_5" price="5" />
<label for="cat_5">cat_5</label>
<br/>
<input type="checkbox" id="cat_6" value="cat_6" price="6.5" />
<label for="cat_6">cat_6</label>
<br/>
<input type="checkbox" id="cat_7" value="cat_7" price="7" />
<label for="cat_7">cat_7</label>
<br/>
<input type="checkbox" id="cat_8" value="cat_8" price="8" />
<label for="cat_8">cat_8</label>
<br/>
<input type="checkbox" id="cat_9" value="cat_9" price="9.5" />
<label for="cat_9">cat_9</label>
</div>
<input type="text" id="total" value="0" />
Instead of looping you can use change which will respond to and change event on the checkbox. Also you need add or subtract value like this += for addition on -= for subtraction
var _total = 0;
$('input[type="checkbox"]').change(function() {
if($(this).is(':checked')){
_total += parseFloat($(this).attr('price')) || 0;
}
else{
_total -= parseFloat($(this).attr('price')) || 0;
}
$('#total').val(_total);
})
JSFIDDLE
$('input:checkbox').change(function(){
var totalprice=0;
$('input:checkbox:checked').each(function(){
totalprice+= parseFloat($(this).attr('price'));
});
$('#total').val(totalprice)
});

PHP pass total value of radio button

How to count the total value of radio button within the same page and pass to another php file? The total will be count at this page and i can get the total from answer.php file.
<form action="answer.php" method="POST">
<input type="radio" name="q1" value="1" />Yes <br />
<input type="radio" name="q1" value="0" />No <br />
<input type="radio" name="q2" value="2" />Yes <br />
<input type="radio" name="q2" value="0" />No <br />
<input type="radio" name="q3" value="3" />Yes <br />
<input type="radio" name="q3" value="0" />No <br />
<input type="submit" value="submit" name="submit"/>
</form>
I suggest using an array to count your values.
<input type="radio" name="q[]" value="2" />
<input type="radio" name="q[]" value="3" />
<input type="radio" name="q[]" value="4" />
<input type="radio" name="q[]" value="5" />
This will result in $_POST['q'] being an array. You can now do:
echo "The total amount is ".array_sum($_POST['q']);
Using jQuery- it is easy, just iterate through the inputs and tally up the values. Note that I gave the form an Id so it can be targetted directly if you have other form. The total can be passed to your other page - either via AJAX or using a standard HTML form as a hidden field. Alternatively - since this is a form and you are already passing it to a PHP page - you could simply submit the form and tally up the $_POST variables on the other side.
$('#testForm input').on('change', function() {
var total=0;
$('input[type=radio]:checked', '#testForm').each(function(){
total += parseInt($(this).val());
})
alert(total)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="testForm" action="answer.php" method="POST">
<input type="radio" name="q1" value="1" />Yes <br />
<input type="radio" name="q1" value="0" />No <br />
<input type="radio" name="q2" value="2" />Yes <br />
<input type="radio" name="q2" value="0" />No <br />
<input type="radio" name="q3" value="3" />Yes <br />
<input type="radio" name="q3" value="0" />No <br />
<input type="submit" value="submit" name="submit"/>
</form>
Commented version for the OP:
$('#testForm input').on('change', function() {//triggers the function on any change in the form
var total=0;//initialises the total at 0 so that each round ottallying up resets before the tally
$('input[type=radio]:checked', '#testForm').each(function(){//selects each input in the #testForm that is checked
total += parseInt($(this).val());//adds the value of each checked radio button to the tally
})
alert(total); //alerts the final tally after all iterations
});
You don't need jquery for this. Add a class to your radio buttons so we can query them without risking getting other elements in the page, something like "my-radio"
This javascript will get you the sum:
function getRadioButtonsSum(radioClass) {
var radioBtns = document.querySelectorAll(radioClass);
var count = 0;
var i;
for (i = 0; i < radioBtns.length; i += 1) {
if (radioBtns[i].checked) {
count += +radioBtns[i].value;
}
}
return count;
}
getRadioButtonsSum('.my-radio');

Categories

Resources