How might I calculate the sum of radio button values using jQuery? - javascript

I am trying to create a form with many groups containing many radio buttons. When the user selects a button, I would like to calculate the sum of each selected radio button value and show this sum to the user.
I have found a plugin for jQuery which will do the calculation, this plugin use the name attribute of the buttons to calculate. For example, it will sum the values of all buttons which have the name sum.
So far, I have tried two ways of setting this up: in the first method, I create a hidden field for each group to hold the sum of the selected values inside it, this hidden field gets the value but the problem is that the total value will not update when a user selects a button. My code looks like this:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Untitled Document</title>
<script src="jquery.js" type="text/javascript">
</script>
<script src="calc.js" type="text/javascript">
</script>
<script src="calc_f.js" type="text/javascript">
</script>
<script type="text/javascript">
function DisplayPrice(price){
$('#spn_Price').val(price);
}
</script>
</head>
<body>
<form id="form1" runat="server">
<input type="hidden" id="spn_Price" name="sum" value="">
<br>
<input id="rdo_1" type="radio" value="159" name="price" onclick="DisplayPrice(this.value);">
<br>
<input id="rdo_2" type="radio" value="259" name="price" onclick="DisplayPrice(this.value);">
<br>
<input type="text" name="totalSum" id="totalSum" value="" size="2" readonly="readonly">
</form>
</body>
</html>
In this code, the input tag with the name totalSum is where the value will update, but it won't update when changing the buttons.
As I said before, the reason why I use a hidden field is to hold each group's subtotal. It has the name sum, which indicates to the plugin that it should be added to others.
I dont know if this is the right way to do this, i have tried to change the name attribute of the buttons when user click them to sum but that didn`t work either!
Here is plugin address : http://www.pengoworks.com/workshop/jquery/calculation/calculation.plugin.htm
How can I do this ?

Plugin schmugin. Get rid of your onclick and try this:
$("input[type=radio]").click(function() {
var total = 0;
$("input[type=radio]:checked").each(function() {
total += parseFloat($(this).val());
});
$("#totalSum").val(total);
});

Untitled Document
<script type="text/javascript">
function DisplayPrice(price){
var val1 = 0;
for( i = 0; i < document.form1.price.length; i++ ){
if( document.form1.price[i].checked == true ){
val1 = document.form1.price[i].value;
}
}
var val2 = 0;
for( i = 0; i < document.form2.price2.length; i++ ){
if( document.form2.price2[i].checked == true ){
val2 = document.form2.price2[i].value;
}
}
var sum=parseInt(val1) + parseInt(val2);
document.getElementById('totalSum').value=sum;
}
</script>
</head>
<body>
Choose a number:<br>
<form name="form1" id="form1" runat="server">
<br>
<input id="rdo_1" type="radio" value="159" name="price" onclick="DisplayPrice(this.value);">159
<br>
<input id="rdo_2" type="radio" value="259" name="price" onclick="DisplayPrice(this.value);">259
<br>
</form>
Choose another number:<br>
<form name="form2" id="form2" runat="server">
<br>
<input id="rdo_1" type="radio" value="345" name="price2" onclick="DisplayPrice(this.value);">345
<br>
<input id="rdo_2" type="radio" value="87" name="price2" onclick="DisplayPrice(this.value);">87
<br>
</form>
<input type="text" name="totalSum" id="totalSum" value="" size="2" readonly="readonly">
</body>
The code above will dinamically sum the checked values from both groups.
parseInt will convert to integers. Use parseFloat otherwise.

Related

Form with input and output immediately reload the page after printing the output

I need to do a simple homework where you enter two integers in two text fields of a form and then you compute the sum and you print it in a "text field (not editable)". My program seems to work but it prints the right output and immediately reload the page. I want the page to remain with the printed output if the user does not click again on "submit" button
Here is my code HTML & JS :
function updateExpr() {
var x1 = document.getElementById("n1").value;
var x2 = document.getElementById("n2").value;
var sum = +x1 + +x2;
document.getElementById("sum").innerHTML = +x1 + +x2;
}
<!DOCTYPE html>
<html>
<head>
<title>Number in a form</title>
<link href="mystyle.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="function.js">
</script>
</head>
<body>
<div id="mainDiv">
<H3>Insert two positive numbers</H3>
<form>
First number:<br>
<input id="n1" type="text" name="firstname"><br>
Second number:<br>
<input id="n2" type="text" name="lastname">
<BR>
<input type="submit" value="Submit" onClick="updateExpr()"/><BR><BR>
</form>
The sum is:<br>
<output id="sum" name="x" for="a b"></output>
</div>
<noscript>
Sorry: Your browser does not support or has disabled javascript
</noscript>
</body>
</html>
When form is submited, the page will be reloaded. To prevent this you should change input type attribute from submit to button.
<input type="submit" value="Submit" onClick="updateExpr()"/>
to
<input type="button" value="Submit" onClick="updateExpr()"/>
You can simply avoid server call by changing your form tag
<form onSubmit="return false">
You dont really need a form to do something like this.
Forms send values to the backend, e.g. a server.
You only want to manipulate some front-end elements like a container to have some new text inside it.
a <form> tag typically sends you to some URI with some aprameters,
this is done by the actions attribute.
<form action="addnames.php">
for example would call the addnames.php script on your server...
You dont need a server tho..look below:
function updateExpr() {
var x1 = document.getElementById("n1").value;
var x2 = document.getElementById("n2").value;
var sum =x1 +x2;
document.getElementById("sum").innerHTML = sum;
}
<h2>HTML Forms</h2>
First name:<br>
<input id="n1" type="text" name="firstname" value="Mickey">
<br>
Last name:<br>
<input id="n2" type="text" name="lastname" value="Mouse">
<br><br>
<button type="submit" onclick="updateExpr()">Submit</button>
<div id="sum">
</div>
<script>
</script>
I would recommand you to add onSubmit method to the form instead of onclick to the input.
Also you better add a return : false to your function and add onsubmit="return updateExpr()".
function updateExpr() {
var x1 = document.getElementById("n1").value;
var x2 = document.getElementById("n2").value;
var sum = +x1 + +x2;
document.getElementById("sum").innerHTML = +x1 + +x2;
return false;
}
<!DOCTYPE html>
<html>
<head>
<title>Number in a form</title>
<link href="mystyle.css" rel="stylesheet" type="text/css"/>
<script type="text/javascript" src="function.js">
</script>
</head>
<body>
<div id="mainDiv">
<H3>Insert two positive numbers</H3>
<form onsubmit="return updateExpr()">
First number:<br>
<input id="n1" type="text" name="firstname"><br>
Second number:<br>
<input id="n2" type="text" name="lastname">
<BR>
<input type="submit" value="Submit" onClick="updateExpr()"/><BR><BR>
</form>
The sum is:<br>
<output id="sum" name="x" for="a b"></output>
</div>
<noscript>
Sorry: Your browser does not support or has disabled javascript
</noscript>
</body>
Another way of doing this would have been to add a button outside of the form linked to the function by onclick event
juste add preventDefault(), like this
function updateExpr(e) {
e.preventDefault();
var x1 = document.getElementById("n1").value;
var x2 = document.getElementById("n2").value;
var sum = +x1 + +x2;
document.getElementById("sum").innerHTML = +x1 + +x2;
}

form with javascript code in wordpress

I want to create same form in wordpress with javascript code as mentioned. Please guide me how to create a similar form and where to post this javascript code. This code is perfectly working when we save this code in html document. But I am unaware where to save this code in wordpress.
Many Thanks
<script type="text/javascript">
function DisplayPrice(price){
var val1 = 0;
for( i = 0; i < document.form1.price.length; i++ ){
if( document.form1.price[i].checked == true ){
val1 = document.form1.price[i].value;
}
}
var val2 = 0;
for( i = 0; i < document.form2.price2.length; i++ ){
if( document.form2.price2[i].checked == true ){
val2 = document.form2.price2[i].value;
}
}
var sum=parseInt(val1) + parseInt(val2);
document.getElementById('totalSum').value=sum;
}
</script>
</head>
<body>
Choose a number:<br>
<form name="form1" id="form1" runat="server">
<br>
<input id="rdo_1" type="radio" value="159" name="price" onclick="DisplayPrice(this.value);">159
<br>
<input id="rdo_2" type="radio" value="259" name="price" onclick="DisplayPrice(this.value);">259
<br>
</form>
Choose another number:<br>
<form name="form2" id="form2" runat="server">
<br>
<input id="rdo_1" type="radio" value="345" name="price2" onclick="DisplayPrice(this.value);">345
<br>
<input id="rdo_2" type="radio" value="87" name="price2" onclick="DisplayPrice(this.value);">87
<br>
</form>
<input type="text" name="totalSum" id="totalSum" value="" size="2" readonly="readonly">
</body>
There are two ways to add this code to wordpress
1 . In your theme folder -> your activated theme -> index.php
2 . In your plugin folder -> create new plugin folder with any name -> add this code by creating index.php file in plugin
add following lines to top of index.php
/*
Plugin Name: name of plugin
Version: 1.0
Plugin URI:
Description:
Author:
Author URL :
activate plugin with name you have given.
test for form.

checking a form before submitting - JavaScript

I have the following form:
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Choose</title>
<script type="javascript/text">
function ischecked(){
var check = document.getElementsByTagName( 'input' );
for( var i = 0; i < check.length; i++ ){
if( check[ i ].type == 'radio' && check[ i ].checked ){
return true;
}
}
return false;
}
</script>
</head>
<body>
<form method="post" enctype="application/x-www-form-urlencoded" onsubmit="ischecked();">
<h1>Choose</h1>
<p><input type="radio" name="choose" value="psychology"><font size="5" color="#0033CC">Instant Psychology</font><br>
<br>
<input type="radio" name="choose" value="geography"><font size="5" color="#CC0000">Instant Geography</font><br>
<br>
<input type="radio" name="choose" value="gastronomy"><font size="5" color="#660033">Instant Gastronomy</font><br>
<br>
<input type="submit" name="Submit" value="Go"></p>
</form>
</body><link rel="stylesheet" type="text/css" href="data:text/css,"></html>
I wanted to make sure one of the radio buttons have been checked before submitting the form. However, it does not work, and the form is submitted anyways. What am I doing wrong here?
You need to return the result of your function from the inline event handler.
You have to check against the value returned in your validation function directly in the attribute value. That is, in your HTML form declaration
<form method="post" enctype="application/x-www-form-urlencoded" onsubmit="ischecked();">
you should write:
onsubmit="return ischecked();"
instead of:
onsubmit="ischecked();"

Add up and change values of 3 text boxes

I have 3 text boxes (testbox, testbox2, testbox3) that get values from an input field, radio button selection and checkbox/tick. The correct values go into testbox, testbox2, testbox3.
However, I need the total of testbox, testbox2, testbox3 to go into text box 'total' - with the total to change if the users selects different radio buttons or tick/unticks etc..
One more thing I need the total to also be shown in the form, echo, (in addition to going into the text box - which will eventually be hidden).
Thank you.
<head>
<script type="text/javascript">
function checkboxClick() {
var textbox = document.forms[0].testbox3;
textbox.value = (textbox.value == 0) ? '1.00' : '0.00';
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<form action="" method="get">
<input name="form1" type="radio" onclick="document.forms[0].testbox2.value='0.00'; "/>
<input name="form1" type="radio" onclick="document.forms[0].testbox2.value='1.00'; "/>
<input name="" type="checkbox" value="" onclick='checkboxClick()'/>
<input name="testbox" type="text" value"2.00"/>
<input name="testbox2" type="text" value"0.00"/>
<input name="testbox3" type="text" value="0.00"/>
<input name="total" type="text" value=""/>
</form>
<body>
</body>
</html>
How about writing a function to update the total (and being careful to parse the textbox inputs as floats):
function updateTotal() {
var textbox1val = parseFloat(document.forms[0].testbox.value);
var textbox2val = parseFloat(document.forms[0].testbox2.value);
var textbox3val = parseFloat(document.forms[0].testbox3.value);
var total = textbox1val + textbox2val + textbox3val;
document.forms[0].total.value = total;
}
And then calling this function in an onchange attribute?

Print values of selected radio buttons and check-boxes and exclude the submit button

In the script below, how do I get the values of only radio buttons and checkboxes that have been selected and not all (provided a radio button and checkbox were selected).
Right now it gives me the values of all, whether selected or not, and also the submit button (which i dont need).
How do i do this? There'll be more checkboxes and radio buttons, i've used only 2 sets for this question.
<html>
<head>
<script type="text/javascript">
function DisplayFormValues()
{
var str = '';
var elem = document.getElementById('frmMain').elements;
for(var i = 0; i < elem.length; i++)
{
str += elem[i].value+"<br>";
}
document.getElementById('lblValues').innerHTML = str;
}
</script>
</head>
<body>
<form id="frmMain" name="frmMain">
<INPUT TYPE="radio" NAME="r1" value="r1a">
<INPUT TYPE="radio" NAME="r1" value="r1b">
<INPUT TYPE="radio" NAME="r1" value="r1c">
<INPUT TYPE="checkbox" NAME="c1" value="c1a">
<INPUT TYPE="checkbox" NAME="c1" value="c1b">
<INPUT TYPE="checkbox" NAME="c1" value="c1c">
<input type="button" value="Test" onclick="DisplayFormValues();" />
</form>
<hr />
<div id="lblValues"></div>
</body>
</html>
Add the following test:
if(elem[i].checked)
str += elem[i].value+"<br>";
Also, if you use jQuery, the whole script is even simpler:
function DisplayFormValues(){
$("input:checkbox:checked").add("input:radio:checked")
.each(function(){
$("div#lblValues").append(this.value + "<br>");
});
}

Categories