cost splitter javascript app - javascript

I am trying to make a cost splitter app for my roommates. I am explaining the app with an example. Suppose we are 4 members, there is a cost of 300, and 3 members (m1, m3, m4) participated in the expenditure (all have an equal share). Among them 2 members have paid the amount as follows: m3 paid 180 and m4 paid 120. Now the balance sheet will look like this:
m1(-100), m2(0), m3(+80), m4(+20)
I am not able to get all the form values properly and make the balance sheet.
<div>
<table id="dashboard">
<tr>
<th>TOTAL</th>
<th>member1</th>
<th>member2</th>
<th>member3</th>
<th>member4</th>
</tr>
<tr>
<td id="total"></td>
<td id="bmem1">0</td>
<td id="bmem2">0</td>
<td id="bmem3">0</td>
<td id="bmem4">0</td>
</tr>
</table>
</div>
<div id="newCostButton">
<button id="showForm" href="#">Add New Cost</button>
</div>
<form id="elForm">
<label>Cost:</label>
<input type="text" id="cost" placeholder="Add new cost">
<br>
<label><b>Participants:</b></label><br>
<span>member1</span>
<input type="checkbox" name="Participant" value="member1">
<span>member2</span>
<input type="checkbox" name="Participant" value="member2">
<span>member3</span>
<input type="checkbox" name="Participant" value="member3">
<span>member4</span>
<input type="checkbox" name="Participant" value="member4">
<br>
<b>contributors:</b><br>
member1
<input class= "contributors" type="text" name="member1">
member2
<input class= "contributors" type="text" name="member2">
member3
<input class= "contributors" type="text" name="member3">
member4
<input class= "contributors" type="text" name="member4">
<input type="submit" id="cal" value="calculate">
</form>
<div id="doc"></div>
<script>
$(function(){
var $newCostButton = $('#newCostButton');
var $elForm = $('#elForm');
var $cost = $('#cost');
$newCostButton.show();
$elForm.hide();
$newCostButton.on('click', function(){
$newCostButton.hide();
$elForm.show();
});
$('input:text').focus(function(){
$(this).val("");
});
function cal(){
var c = $cost.val();
var part = $('input:checked');
pCount = part.length;
var d= parseInt(c/pCount);
var contributors = $('.contributor');
var mem = [];
contributors.each(function(){
mem.push(parseInt($(this).val()));
});
console.log(mem);
for(var i=0;i<pCount;i++){
var r = mem[i]-d;
console.log(r);
}
}
$elForm.on('submit', function(e){
e.preventDefault();
cal();
});
</script>

I don't see where you import jquery
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
why don't you use excel or google sheets?

I think this does something similar to what you are asking for. I simplified a few things like .hide() and .show(), but they're easy enough to add back. Hopefully something in here helps. If not, it was still a fun hour code challenge.
html:
<div>
<table class="dashboard">
<tr>
<th>TOTAL</th>
<th>member1</th><th>member2</th><th>member3</th<th>member4</th>
</tr>
<tr>
<td>0</td><td>0</td><td>0</td><td>0</td><td>0</td>
</tr>
</table>
</div>
<div class="newCost">
<span>Cost:</span><input type="text" placeholder="Add New Cost">
<button>Add New Cost</button>
</div>
<div class="participants">
<p>Participants:</p>
<span>member1</span><input type="checkbox">
<span>member2</span><input type="checkbox">
<span>member3</span><input type="checkbox">
<span>member4</span><input type="checkbox">
</div>
<div class="contributors">
<p>Contributors:</p>
member1 <input type="text">
member2 <input type="text">
member3 <input type="text">
member4 <input type="text">
</div>
<button class="calculate">calculate</button>
javascript:
String.prototype.toInt = function() { return parseInt(this, 10); };
$('.newCost button').on('click', function() {
let newCost = $('.newCost input').val().toInt();
$('.dashboard td')
.each(function(index, td) {
td.textContent = td.textContent.toInt() + (index ? newCost / 4 : newCost);
});
});
$('button.calculate').on('click', function() {
$('.participants input').each(function(index){
if (this.checked) {
this.checked = false;
let currentOwed = $(`.dashboard td:eq(${index + 1})`).text().toInt();
let contributed = $(`.contributors input:eq(${index})`).val().toInt();
let total = $('.dashboard td:eq(0)').text().toInt();
$('.dashboard td:eq(0)').text(total -= contributed);
$(`.dashboard td:eq(${index + 1})`).text(currentOwed -= contributed);
}
});
});
$('button').click(()=> { $('input[type=text]').val(''); });
https://jsfiddle.net/wn7bbxjk/

Related

How to get the average of all the dynamic inputs

I can't find the average of all the inputs. My code only reads the input that i stated in html, but doesn't read the other dynamic ones.
Heres my code:
$(document).ready(function(){
// adds a new row
$(".addCF").click(function(){
$("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> Add Remove</td></tr>');
});
// deletes the row
$("#customFields").on('click','.remCF',function(){
$(this).parent().parent().remove();
});
$("#customFields").on('click','.add',function(){
$("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> Add Remove</td></tr>');
});
$("#click").click(function(){
var isbn = document.getElementById('customFieldName').value;
alert(isbn / $("input").length)
$("#averageGrade").text("Average Grade: " + isbn)
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="form-table" id="customFields">
<tr valign="top">
<th scope="row"><label for="customFieldName">Custom Field</label></th>
<td>
<input type="text" class="code" id="customFieldName" name="customFieldName[]" placeholder="Input Name" />
Add
</td>
</tr>
</table>
<button id = "click" class = "btn btn-primary" >Hi</button>
<p id = "averageGrade">Average Grade:</p>
Please help!
Thanks!
Each element.id must be unique - please change customFieldName to a class, and then iterate over the inputs and calculate the average. Also, you can reuse the same class for all "add" buttons and save that string in a variable so you don't have to paste it multiple times.
let inputTemplate = '<tr valign="top"><th scope="row"><label>Custom Field</label></th><td><input type="text" class="customFieldName code" name="customFieldName[]" value="" placeholder="Input Name" /> Add Remove</td></tr>';
$(document).ready(function() {
// adds a new row
$("#customFields").on('click', '.addCF', function() {
$("#customFields").append(inputTemplate);
});
// deletes the row
$("#customFields").on('click', '.remCF', function() {
$(this).parent().parent().remove();
});
$("#click").click(function() {
let fields = $('.customFieldName'),
total = 0;
for (let field of fields)
total += Number(field.value);
let average = total / fields.length;
$("#averageGrade").text("Average Grade: " + average);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="form-table" id="customFields">
<tr valign="top">
<th scope="row"><label>Custom Field</label></th>
<td>
<input type="text" class="customFieldName code" name="customFieldName[]" placeholder="Input Name" />
Add
</td>
</tr>
</table>
<button id="click" class="btn btn-primary">Hi</button>
<p id="averageGrade">Average Grade:</p>
First of all, you need a way to select all the fields. Since id must (should) be unique, you could use the name or the class .code and remove id="customFieldName".
Then, getElementById, as its name suggests, returns one element. You need to select them all! If you're using class names, you can use getElementsByClassName, or querySelectorAll, or, since you're already using jQuery, just $(".code"), along with a loop to read each input's value (it you use jQuery, you can also use each()).
var sum=0,count=0,average;
$(".code").each(function() {
var value=parseInt($(this).val());
//You may want to validate the field
if(!isNaN(value)) sum+=value;
count++;
});
average=sum/count;
...
As many has pointed out (including myself in the comment section), you are going about using the wrong selector. id is a unique selector, meaning that the script will look at the first instance of the id and then stop immediately after.
What you need to do is use a selector that goes through every occurance of its instance. This is why class selectors exist. That will be the first fix in your code.
How I would go about calculating the average, personally, would be to make an array and push(); the values of the grades into the array. We will also need to do a parseInt() to make sure that our values are in fact handled as numbers. Otherwise, they'll be interpreted as strings.
You will then need to loop through the array, sum the values and divide by the length of the array.
HTML Example:
<div class="row">
<div class="col-12">
<table class="table form-table" id="customFields">
<tr valign="top">
<th scope="row"><label>Custom Field</label></th>
<td>
<input type="number" class="customFieldName" placeholder="Input Number" />
Add
</td>
</tr>
</table>
</div>
</div>
<div class="row">
<div class="col-md-4">
<button id="calcAvrgBtn" class="btn-primary">Calculate average grade</button>
</div>
<div class="col-md-4">
<p id="averageCalc"></p>
</div>
</div>
jQuery Example:
$('.addCF').on("click", function() {
$("#customFields").append('<tr valign="top"><th scope="row"><label>Custom Field</label></th><td><input type="number" class="customFieldName" placeholder="Input Number" /> Remove</td></tr>');
});
$(document).on("click", "a.remCF" , function() {
$(this).parent().parent().remove();
});
$('#calcAvrgBtn').on("click", function() {
let gradeArr = [];
$('.customFieldName').each(function() {
gradeArr.push(parseInt($(this).val()));
});
let total = 0;
for(var i = 0; i < gradeArr.length; i++) {
total += gradeArr[i];
}
let avg = total / gradeArr.length;
$('#averageCalc').text("The average grade is: "+avg);
});
Codepen example can be found here.
Snippet Example:
$('.addCF').on("click", function() {
$("#customFields").append('<tr valign="top"><th scope="row"><label>Custom Field</label></th><td><input type="number" class="customFieldName" placeholder="Input Number" /> Remove</td></tr>');
});
$(document).on("click", "a.remCF" , function() {
$(this).parent().parent().remove();
});
$('#calcAvrgBtn').on("click", function() {
let gradeArr = [];
$('.customFieldName').each(function() {
gradeArr.push(parseInt($(this).val()));
});
let total = 0;
for(var i = 0; i < gradeArr.length; i++) {
total += gradeArr[i];
}
let avg = total / gradeArr.length;
$('#averageCalc').text("The average grade is: "+avg);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row">
<div class="col-12">
<table class="table form-table" id="customFields">
<tr valign="top">
<th scope="row"><label>Custom Field</label></th>
<td>
<input type="number" class="customFieldName" placeholder="Input Number" />
Add
</td>
</tr>
</table>
</div>
</div>
<div class="row">
<div class="col-md-4">
<button id="calcAvrgBtn" class="btn-primary">Calculate average grade</button>
</div>
<div class="col-md-4">
<p id="averageCalc"></p>
</div>
</div>

how to select multiple checkbox validation in javascript

Here is my Form. I need validation in JavaScript.
At least one checkbox selected in validation.
I hop you all are understand what I need.
please give me solution for that.
If any query then feel free ask.
<form action="#" method="post" name="studentregistration" onsubmit="return(validate());">
<table cellpadding="3" width="100%" align="center" cellspacing="3">
<tr>
<td>Hobby</td>
<td>
<input type="checkbox" name="hobby" value="Chess" id="hobby">Chess
<input type="checkbox" name="hobby" value="Music" id="hobby">Music<br>
<input type="checkbox" name="hobby" value="Cricket" id="hobby">Cricket
<input type="checkbox" name="hobby" value="Reading" id="hobby">Reading
</td>
</tr>
<tr>
<td>
<input type="submit" name="Submit Form" value="Submit Form" id="submitform">
</td>
</tr>
</table>
</form>
If you're trying to validate that at least one checkbox is checked, then this should work for you using jQuery:
$('input[type="checkbox"]:checked').length > 0
In "pure" js, you could remove the onsubmit attribute and do this instead:
document.querySelector('form[name="studentregistration"]').onsubmit = function(e) {
e.preventDefault();
var cbx = document.querySelectorAll('form[name="studentregistration"] input[name="hobby"]:checked');
if(cbx.length > 0) {
// at least one checked - do something
}
else {
// none checked
}
}
See a live demo!
Complete solution.
In order to submit the form after validation you must use:
document.getElementById("myForm").submit();
document.getElementById("submitform").addEventListener("click",submit_form);
function submit_form(e){
var ob = "";
var chess = document.getElementById("hobby1").checked;
var music = document.getElementById("hobby2").checked;
var cricket = document.getElementById("hobby3").checked;
var reading = document.getElementById("hobby4").checked;
if(chess == true){
ob += "hobby: chess selected!\n";
}
if(music == true){
ob += "hobby: music selected!\n";
}
if(cricket == true){
ob += "hobby: cricket selected!\n";
}
if(reading == true){
ob += "hobby: reading selected!\n";
}
if(ob==""){
alert("No hobbys selected");
}
else{
alert(ob);
//document.getElementById("myForm").submit();
}
//for testing purposes
e.preventDefault();
return false;
}
<form id = "myForm" action="#" method="post" name="studentregistration">
<table cellpadding="3" width="100%" align="center" cellspacing="3">
<tr>
<td>Hobby</td>
<td>
<input type="checkbox" name="hobby" id="hobby1">Chess
<input type="checkbox" name="hobby" id="hobby2">Music<br>
<input type="checkbox" name="hobby" id="hobby3">Cricket
<input type="checkbox" name="hobby" id="hobby4">Reading
</td>
</tr>
<tr>
<td>
<input type="button" name="Submit Form" value="Submit Form" id="submitform">
</td>
</tr>
</table>
</form>
if($("#hobby").is(':checked')){
alert("checkbox checked");
}
else{
alert("Please select at least one checkbox");
}
Here is another easy answer
var test = document.getElementsByName("hobby[]");
if(test[0].checked==false && test[1].checked==false && test[2].checked==false && test[3].checked==false)
{
alert("Please Check");
return false;
}

Getting rendering html from angular controller

I am developing a web with Angular, Ninja, HTML5 and Javascript. My problem is the following: I have a Ninja controller (ProjectController) where I render a list of projects to the HTML. I would like to show this list with the names of the projects with Angular. All the examples I have seeing about this, they made the list manually like this:
(function() {
var app = angular.module('projectStore', []);
app.controller('ProjectController', function(){
this.projects = gems ;
});
var gems = [
{ name: 'Azurite' },
{ name: 'Bloodstone' },
{ name: 'Zircon'}
];
})();
This is my code:
ProjectController.java
public Result getList(final FlashScope flashScope, final Session rawSession, final ProjectData registerRequest) {
log.info("getting project List");
List<Record1<String>> list = jCtx.jooq().select(PROJECT.PROJECT_NAME).from(PROJECT).fetch();
return Results.html().template("/views/ProjectController/projects.ftl.html").render("projects", list.toString());
}
rendered HTML projects.ftl.html
<#import "../layout/defaultLayout.ftl.html" as layout>
<#layout.myLayout "Home page">
<form name ="test" action="/projects" method="post" ng-app="projectStore">
<table id = "table_projects_header">
<tr>
<td>Projects</td>
<td style="padding-right:10px; padding-left:40px"> <input type="button" value=" + " onclick="addRow('table_projects')" /> </td>
<td> <input type="button" value=" - " /> </td>
</tr>
<tr id = "table_projects_list">
</tr>
</table>
<input type="submit" value="Add Project"/>
<div ng-controller="ProjectController as controller">
<div class="project row" ng-repeat="project in controller.projects">
<h3>
{{project}}
</h3>
</div>
</div>
</form>
</#layout.myLayout>
And I would like to do something like this:
app.js
(function() {
var app = angular.module('projectStore', []);
app.controller('ProjectController',function(){
this.projects = **get projects from rendered html** ;
});
})();
Is that possible??Thank you in advance!
HTML
<form name ="test" action="/projects" method="post" ng-app="projectStore">
<table id = "table_projects_header">
<tr>
<td>Projects</td>
<td style="padding-right:10px; padding-left:40px"> <input type="button" value=" + " onclick="addRow('table_projects')" /> </td>
<td> <input type="button" value=" - " /> </td>
</tr>
<tr id = "table_projects_list" class="renderValues">
</tr>
</table>
<input type="submit" value="Add Project"/>
<div ng-controller="ProjectController as controller">
<div class="project row" ng-repeat="project in controller.projects">
<h3>
{{project}}
</h3>
</div>
</div>
</form>
You can do like is:
(function() {
var app = angular.module('projectStore', []);
app.controller('ProjectController',function(){
this.projects=[];
//javascript way
var elements = document.getElementsByClassName('renderValues');
for (var index in elements)
{
var element = elements[index];
this.projects.push(element.innerHTML);
}
//jQuery way
/* var elements = document.getElementsByClassName('');
$('.renderValues').each(function(){
this.projects.push($(this).text());
});*/
});
})();

2 Identical javascripts don't run with jquery accordian

Ok, here I have a Jquery Accordian with 2 tabs.
1 is for SELL and the other one is BUY.Each one of them has it's own group of input boxes and javascript attached to them.
Here's for the BUY tab
Input Boxes:-
<tr>
<td>BUY <input type="text" name="buybtc" id="buybtc" class="validate[required] text-input" placeholder="amount" size="10"> BTC </td>
<td>At Rate<input type="text" name="rate" id="rate" class="validate[required] text-input" placeholder="rate" size="10">BTC/LTC</td>
</tr>
<tr>
<td>LTC You will give<input type="text" name="giveltc" readonly id="giveltc" size="10"></td>
</tr>
Javascript:-
<script type="text/javascript">
window.onload = function(){
var buybtc = document.getElementById('buybtc'), //get the amount BTC to be sold
giveltc = document.getElementById('giveltc'),
rate = document.getElementById('rate');
var constantNumber = 0.022632;
rate.onkeyup = function () {
var result = parseFloat(buybtc.value) * parseFloat(rate.value);
giveltc.value = !isNaN(result) ? result : '';
};
}
//sellbtc = buybtc
//getltc = giveltc
</script>
SELL Tab :-
Input Boxes
<tr>
<td>Sell <input type="text" name="sellbtc" id="sellbtc" class="validate[required] text-input" placeholder="amount"> BTC </td>
<td>At Rate<input type="text" name="rates" id="rates" class="validate[required] text-input" placeholder="rate">LTC/BTC</td>
</tr>
<tr>
<td>LTC You will get<input type="text" name="getltc" readonly id="getltc"></td>
</tr>
Javascript :-
<script type="text/javascript">
window.onload = function(){
var sellbtc = document.getElementById('sellbtc'), //get the amount BTC to be sold
getltc = document.getElementById('getltc'),
rate = document.getElementById('rate');
var constantNumber = 0.022632;
rate.onkeyup = function () {
var result = parseFloat(sellbtc.value) * parseFloat(rate.value);
getltc.value = !isNaN(result) ? result : '';
};
}
</script>
The work of both these scripts is to calculate the total amount based on the principle amount and rate.The problem is, that when I put only 1 javascript in the page (for the buy tab)..everything works fine..i.e, the amount is calculated in the third box.But, the moment I place the javascript for the BUY tab..both the javascripts stop working, that means the final amount is not calculated in any of these tabs.
How should I tackled this problem?
Thanks.
Updated:-
<script type="text/javascript">
window.onload = function(){
var sellbtc = document.getElementById('sellbtc'), //get the amount BTC to be sold
getltc = document.getElementById('getltc'),
rate = document.getElementById('rate');
var constantNumber = 0.022632;
rate.onkeyup = function () {
var result = parseFloat(sellbtc.value) * parseFloat(rate.value);
getltc.value = !isNaN(result) ? result : '';
};
}
</script>
<script type="text/javascript">
window.onload = function(){
var buybtc = document.getElementById('buybtc'), //get the amount BTC to be sold
giveltc = document.getElementById('giveltc'),
rateSell = document.getElementById('rateSell');
var constantNumber = 0.022632;
rate.onkeyup = function () {
var resultSell = parseFloat(buybtc.value) * parseFloat(rateSell.value);
giveltc.value = !isNaN(resultSell) ? resultSell : '';
};
}
//sellbtc = buybtc
//getltc = giveltc
</script>
<div id="accordion">
<h3>Buy</h3>
<div>
<p>
<form action="tradehandler.php?action=buy" method="post" id="formID">
<table>
<tr>
<td>BUY <input type="text" name="buybtc" id="buybtc" class="validate[required] text-input" placeholder="amount" size="10"> BTC </td>
<td>At Rate<input type="text" name="rateSell" id="rateSell" class="validate[required] text-input" placeholder="rate" size="10">BTC/LTC</td>
</tr>
<tr>
<td>LTC You will give<input type="text" name="giveltc" readonly id="giveltc" size="10"></td>
</tr>
<tr>
<td><input type="submit" name="submit"></td>
</tr>
</table>
</form>
</p>
</div>
<h3>Sell</h3>
<div>
<p>
<form action="tradehandler.php?action=sell" method="post" id="formID">
<table>
<tr>
<td>Sell <input type="text" name="sellbtc" id="sellbtc" class="validate[required] text-input" placeholder="amount"> BTC </td>
<td>At Rate<input type="text" name="rate" id="rate" class="validate[required] text-input" placeholder="rate">LTC/BTC</td>
</tr>
<tr>
<td>LTC You will get<input type="text" name="getltc" readonly id="getltc"></td>
</tr>
<tr>
<td><input type="submit" name="submit"></td>
</tr>
</table>
</form>
</p>
</div>
</div>
this work only for sell div
<script type="text/javascript">
window.onload = function(){
setAccordion('sellbtc','getltc','rates');
};
}
function setAccordion(btc,ltc,rate)
{
var sellbtc = document.getElementById(btc), //get the amount BTC to be sold
getltc = document.getElementById(ltc),
rateVar = document.getElementById(rate);
var constantNumber = 0.022632;
rateVar.onkeyup = function () {
var result = parseFloat(sellbtc.value) * parseFloat(rate.value);
getltc.value = !isNaN(result) ? result : '';
}
</script>
if they are on the same page, you have to change the ID of rates and ltc in the SELL div
and change the script like this:
<script type="text/javascript">
window.onload = function(){
setAccordion('buybtc','getltc','rates');
setAccordion('sellbtc','SELLgetltc','SELLrates');
};
}
function setAccordion(btc,ltc,rate)
{
var sellbtc = document.getElementById(btc), //get the amount BTC to be sold
getltc = document.getElementById(ltc),
rateVar = document.getElementById(rate);
var constantNumber = 0.022632;
rateVar.onkeyup = function () {
var result = parseFloat(sellbtc.value) * parseFloat(rate.value);
getltc.value = !isNaN(result) ? result : '';
}
</script>

Stuck trying to assign JS vars to hidden fields

I've been fighting with this for a couple of days now...need some guidance please.
I have pared down a much bigger form to a "sample" size to demonstrate what I am after.
The area in question is blocked off in a very recognizable area in the calcFees function.
I also tried to get fancy and have the vars self post to the form so they could be seen, but that does not work.
UPDATE: Here is a bit more info as to what I am running into.
//At this point the var regularfee is = 26.5
// (confirmed by console.log(regularfee);)
// I want to assign it to the hidden field with the id="regularfee"
// I have tried both of the following lines:
document.getElementById('regularfee').value=regularfee.value;
// console.log(document.getElementById('regularfee.value')); shows "null"
document.getElementById('regularfee').value=regularfee;
// console.log(document.getElementById('regularfee')); shows "[object HTMLDivElement]"
What am I doing wrong?
END OF UPDATE *****************************
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form id="multiForm" action="post.php" method="POST" id="app" name="app">
<div id="page1" class="page" style="visibility:visible;">
Name: <input type="text" size="40" name="name1" >
<br><br>
<table border="1" cellpadding="5" width="50%">
<tbody>
<tr>
<td align="center" colspan="3"><strong>Membership Classification</strong></td>
</tr>
<tr><td width="1000">
<input name="paymethod" type="radio" class="pay" id="paypal" value="paypal" />I would like to use PayPal   
<input name="paymethod" type="radio" class="pay" id="check" value="check" />I would like to pay by check
</td>
<td style="width:150px" align="right">Fee
</td>
<td style="width:150px">
</td></tr>
<tr>
<td><input name="memberclass" type="radio" class="membership" id="regular" value="regular"/> Regular Membership</td>
<td align="right"><div id=regularfee></td>
<td><div align="right" id=regselectedfee></td>
</tr>
<tr><td colspan="2" align="right">Total </td>
<td><div align="right" id=total>
</td></tr></tbody>
</table>
<input type="hidden" name="regularfee" id="regularfee" value="">
<input type="hidden" name="regselectedfee" id="regselectedfee" value="">
<input type="hidden" name="total" id="total" value="">
</form>
<br>
<input type="button" id="C1" value="Continue" onClick="showLayer('page2')">
</td></tr>
</table>
</div>
<div id="page2" class="page">
<b>Page 2
<br><br>
<input type="button" id="B1" value="Go Back" onClick="showLayer('page1')">
<input type="submit" name="submit" value="Click to see Vars" />
</div>
</form>
</body>
</html>
<script type="text/javascript" src="jquery-1.10.2.min.js"></script>
<script language="JavaScript">
var paypalselected
var checkselected
var regularfee
var memberfee1
var total
$(function () {
function clearForm()
{
paypalselected = "0";
checkselected = "0";
regularfee = 0.0;
memberfee1 = 0.0;
total = 0.0;
$("#regselectedfee").text(memberfee1.toFixed(2));
$("#total").text(total.toFixed(2));
// clear all radio buttons
$("#regular").prop("checked", false );
}
function calcFees()
{
total = (memberfee1);
$("#total").text(total.toFixed(2));
// **********************************************************************************
// Here is where I want to plug in the 3 JS vars to the hidden fields
// regularfee, regselectedfee, total
// Here is what I've tried:
// vars are not getting plugged in
// If possible, I would like the vars to be plugged in dynamically
// just as the form is updateddynamically when user selects buttons
document.getElementById('regularfee').value=regularfee;
document.getElementById('regselectedfee').value=regselectedfee;
document.getElementById('total').value=total;
// **********************************************************************************
}
function selectPayment()
{
$(".pay").change(function () {
clearForm();
if ($("#paypal").prop("checked")) {
regularfee = 26.50;
$("#regularfee").text(regularfee.toFixed(2));
paypalselected = "1";
checkselected = "0";
}
if ($("#check").prop("checked")) {
regularfee = 25.0;
$("#regularfee").text(regularfee.toFixed(2));
checkselected = "1";
paypalselected = "0";
}
});
}
clearForm();
selectPayment();
//start of membership button selection
$(".membership").change(function () {
if (paypalselected == "1"){
if ($("#regular").prop("checked")) {
memberfee1 = 26.5;
$("#regselectedfee").text(memberfee1.toFixed(2));
calcFees();
}
} //end of paypalselected test
if (checkselected == "1"){
if ($("#regular").prop("checked")) {
memberfee1 = 25.0;
$("#regselectedfee").text(memberfee1.toFixed(2));
calcFees();
}
} //end of checkselected test
}); //end of $(".membership").change(function () {
});
//end of main function
var currentLayer = 'page1';
function showLayer(lyr){
hideLayer(currentLayer);
document.getElementById(lyr).style.visibility = 'visible';
currentLayer = lyr;
window.scrollTo(0,0);
}
function hideLayer(lyr){
document.getElementById(lyr).style.visibility = 'hidden';
}
</script>
<style>
body{
font: 10pt sans-serif;
}
.page{
position: absolute;
top: 10;
left: 100;
visibility: hidden;
}
p.small
{
line-height: 5px;
}
p.smalltext12
{
font-size:12px
}
</style>
You have 2 elements #total. Only the first is given a value:
document.getElementById('total').value = total;
Same for the others.
IDs must be unique to be useful.

Categories

Resources