I Want to hide element if another div's length is greater than 0, otherwise show the div
i have this code but it is not working for me :(
<div id="myid">90.00</div>
<div class="myclass">99.00</div>
JS code
$(document).ready(function() {
if($('#myid').length > 2){
$('.myclass').hide();
}
});
First edit your question by your new detail;
Then set your condition inside your updateTotalFinal function
jQuery(document).ready(function() {
function updateTotalFinal(){
const subtotalValue = +jQuery('.wpforms-payment-total').text().replace(/^[^0-9,.]+/, "").match( /^[0-9,.]+/g, '');
let totalValue = subtotalValue;
const totalFinalElem = jQuery("#totalfinal");
jQuery("input.change-total:checked").each(function() {
const $this = jQuery(this);
if ($this.is("[data-method=add]")) {
totalValue = totalValue * $this.data("amount");
} else if ($this.is("[data-method=multiply]")) {
totalValue += subtotalValue * $this.data("amount");
}
});
totalFinalElem.text(`${totalValue.toFixed(2)}`);
// IF YOU WANT CHECK THAT ANY VALUE FOR totalfinal IS EXIST USE THIS
if($('#totalfinal').text().length ){
$('.wpforms-payment-total').hide();
}
// IF YOU WANT CHECK THAT totalfinal IS GREATHER THAN ZERO USE THIS
/* if(parseInt( $('#totalfinal').text()) > 0 ){
$('.wpforms-payment-total').hide();
} */
}
jQuery("input.change-total").on("change", function() {
updateTotalFinal();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wpforms-payment-total">
97
</div>
<tr>
<td>
<input type="checkbox" class="change-total" name="myBox2" size="12" data-amount="0.15" data-method="multiply" value="100" />
With Two Coat + 15%
</td>
<td>
<input type="checkbox" class="change-total" name="myBox3" size="12" id="myCheck" data-amount="0.9" data-method="add" />
With My Own Paint
</td>
</tr>
<br>
<b><span id="totalfinal"></span></b>
i have this code and want to hide
class "wpforms-payment-total" when "totalfinal" is calculated
<div class="wpforms-payment-total">
97
</div>
<tr>
<td>
<input type="checkbox" class="change-total" name="myBox2" size="12" data-amount="0.15" data-method="multiply" value="100" />
With Two Coat + 15%
</td>
<td>
<input type="checkbox" class="change-total" name="myBox3" size="12" id="myCheck" data-amount="0.9" data-method="add" />
With My Own Paint
</td>
</tr>
<br>
<b><span id="totalfinal"></span></b>
JS
jQuery(document).ready(function() {
function updateTotalFinal(){
const subtotalValue = +jQuery('.wpforms-payment-total').text().replace(/^[^0-9,.]+/, "").match( /^[0-9,.]+/g, '');
let totalValue = subtotalValue;
const totalFinalElem = jQuery("#totalfinal");
jQuery("input.change-total:checked").each(function() {
const $this = jQuery(this);
if ($this.is("[data-method=add]")) {
totalValue = totalValue * $this.data("amount");
} else if ($this.is("[data-method=multiply]")) {
totalValue += subtotalValue * $this.data("amount");
}
});
totalFinalElem.text(`$ ${totalValue}`);
}
jQuery("input.change-total").on("change", function() {
updateTotalFinal();
});
});
$(document).ready(function() {
if($('#totalfinal').text() > 0){
$('.myclass').hide();
}
});
Related
i heve calucalot problem with jquery.
Custom Wpform Checkbox Field returning NaN.
HTML
<div class="wpforms-payment-total">
$ 85
</div>
<input type="checkbox" name="myBox2" size="12" />
With Two Coat + 15%
<b><span id="totalfinal"></span> </b>
JS
jQuery(document).ready(function() {
var Valuee = $('.wpforms-payment-total');
jQuery('input[name="myBox2"]').on('click', function() {
if (jQuery(this).is(':checked')) {
var finalprice = parseInt($('.wpforms-payment-total').text()) * 1.15;
jQuery('#totalfinal').text(finalprice.toFixed(2));
} else {
var finalprice = parseInt($('.wpforms-payment-total').text());
jQuery('#totalfinal').text(finalprice.toFixed(2));
}
});
});
You can not parse any String to a number, you can either split your total amount in a prefix and a number oder you have to remove anything but the number from the string.
As I think storing the number in its own Tag makes more sense, here is a working snipet that does that.
jQuery(document).ready(function() {
const Valuee = $('.wpforms-payment-total');
jQuery('input[name="myBox2"]').on('click', function() {
let finalprice = parseInt(Valuee.text().replace(/^[^0-9,.]+/, "").match( /^[0-9,.]+/g, '')[0]);
if (jQuery(this).is(':checked')) {
finalprice *= 1.15;
}
jQuery('#totalfinal').text(finalprice.toFixed(2));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wpforms-payment-total">
$ 85
</div>
<input type="checkbox" name="myBox2" id="myBox2" size="12" />
<label for="myBox2">With Two Coat + 15%</label>
<br>
<b><span id="totalfinal"></span></b>
Here is another methode, using data attributes to make it more versityle, maybe that is something you might want to learn about when dealing with jQuery:
jQuery(document).ready(function() {
function updateTotalFinal(){
const subtotalValue = +jQuery('.wpforms-payment-total').text().replace(/^[^0-9,.]+/, "").match( /^[0-9,.]+/g, '')[0];
let totalValue = subtotalValue;
const totalFinalElem = jQuery("#totalfinal");
jQuery("input.change-total:checked").each(function() {
const $this = jQuery(this);
if ($this.is("[data-method=add]")) {
totalValue += +$this.data("amount");
} else if ($this.is("[data-method=multiply]")) {
totalValue += subtotalValue * $this.data("amount");
}
});
totalFinalElem.text(`$ ${totalValue}`);
}
jQuery("input.change-total").on("change", function() {
updateTotalFinal();
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wpforms-payment-total">
85€
</div>
<label>
<input type="checkbox" class="change-total" name="myBox2" size="12" data-amount="0.15" data-method="multiply" />
With Two Coat + 15%
</label>
<br>
<label>
<input type="checkbox" class="change-total" name="myBox3" size="12" data-amount="5" data-method="add" />
With extra Pants + $ 5
</label>
<br>
<b><span id="totalfinal">$ 85</span></b>
You must first remove all non-digits character from price then use that,
Notice that for checkbox it is better to use change event
jQuery('input[name="myBox2"]').on('change', function() {
// Remove any non-digits character
var price = parseInt($('.wpforms-payment-total').text().replace( /^\D+/g, ''));
if (jQuery(this).is(':checked')) {
var finalprice = price * 1.15;
jQuery('#totalfinal').text(finalprice.toFixed(2));
} else {
jQuery('#totalfinal').text(price.toFixed(2));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wpforms-payment-total">
$ 85
</div>
<input type="checkbox" name="myBox2" size="12" />
With Two Coat + 15%
<b><span id="totalfinal"></span> </b>
This is a table for user to record Expenses and Amount. User can add table cell to record more items with the amount. After user key in the Amount, it will show 7% tax at beside and total amount at the top. But now i am facing 2 problems.
If user added 2 items, and input the 2 items' amount, then if they deleted the row, the total amount will not deduct after the row is deleted.
the tax will only added in first row. I want to do it in each row with 7% tax with each item's amount.
So can i know how to solve this 2 problems?
function validate(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /[0-9]|\./;
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
}
function force2decimals(event) {
var value = $(event).val();
var format_val = parseFloat(value).toFixed(2);
$(event).val(format_val);
}
//<----------------------2 Decimal force END-------------------->
// +
function mFunction() {
document.getElementById("rowrow").insertRow(-1).innerHTML =
'<tr><td></td><td><output id="gst">0.00</output></td><td><input type="text" name="Amount[]" id="columninput" class="input" oninput="myFunction(this.value)" placeholder="Amount" style="font-size:14px;" min="0" lang="en-150" onchange="force2decimals(this)" onkeypress="validate(event)" inputmode="numeric"></td></tr>';
}
// -
function remove() {
var x = document.getElementById("rowrow").rows.length;
if (x == 1) {} else {
document.getElementById("rowrow").deleteRow(-1);
};
}
function myFunction() {
const ele = document.querySelectorAll('input.input');
let sum = 0;
ele.forEach(input => {
sum += input.value ? parseFloat(input.value) : 0;
});
document.getElementById('result').textContent = sum.toFixed(2);
document.getElementById('gst').textContent = (sum * 0.07).toFixed(2);
}
.css-serial {
counter-reset: serial-number;
}
.css-serial td:first-child:before {
counter-increment: serial-number;
content: counter(serial-number);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<div id="container">
<div id="body">
<br>
<div class="row">
<div class="css-serial" style="overflow-x:auto;">
<table id="rowrow">
<tr>
<td id="number"></td>
<td><output id="gst">0.00</output></td>
<td><input type="text" name="Amount[]" class="input" oninput="myFunction(this.value)" id="columninput" placeholder="Amount" style="font-size:14px;" min="0" lang="en-150" onchange="force2decimals(this)" onkeypress='validate(event)' inputmode='numeric'
required></td>
Total Amount <output id="result"> 0.00 </output>
<input type="button" id="slipbutton1" onclick="mFunction();" name='add' value="+" />
<input type="button" id="slipbutton2" onclick="remove();" name='remove' value="-" /><br><br>
</table>
</div>
</div>
<br>
</div>
</div>
I have managed to make changes as per your need, also I have used jquery as you had added into your code.
I have calculated output in the remove() you can move it to a common function to avoid dirty code.
function remove() {
var x = document.getElementById("rowrow").rows.length;
if (x == 1) {} else {
var ele = document.querySelectorAll('input.input');
let sum = 0;
ele.forEach(input => {
sum += input.value ? parseFloat(input.value) : 0;
});
sum = sum - ele[ele.length - 1].value;
document.getElementById('result').textContent = sum.toFixed(2);
document.getElementById("rowrow").deleteRow(-1);
};
}
Changed GST id to class, as id should be unique.
Added this line of code to print GST into each row.
$(input).parents("tr").find(".gst").text((input.value * 0.07).toFixed(2));
you had added 2 class attributes to input in JS template, also merged them.
<tr>
<td></td>
<td><output class="gst">0.00</output></td>
<td>
<input
type="text"
name="Amount[]"
class="columninput input" // This line
oninput="myFunction(this.value)"
placeholder="Amount"
style="font-size:14px;"
min="0" lang="en-150"
onchange="force2decimals(this)"
onkeypress="validate(event)"
inputmode="numeric"
>
</td>
</tr>
function validate(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode(key);
var regex = /[0-9]|\./;
if (!regex.test(key)) {
theEvent.returnValue = false;
if (theEvent.preventDefault) theEvent.preventDefault();
}
}
function force2decimals(event) {
var value = $(event).val();
var format_val = parseFloat(value).toFixed(2);
$(event).val(format_val);
}
//<----------------------2 Decimal force END-------------------->
// +
function mFunction() {
document.getElementById("rowrow").insertRow(-1).innerHTML =
'<tr><td></td><td><output class="gst">0.00</output></td><td><input type="text" name="Amount[]" class="columninput input" oninput="myFunction(this.value)" placeholder="Amount" style="font-size:14px;" min="0" lang="en-150" onchange="force2decimals(this)" onkeypress="validate(event)" inputmode="numeric"></td></tr>';
}
// -
function remove() {
var x = document.getElementById("rowrow").rows.length;
if (x == 1) {} else {
var ele = document.querySelectorAll('input.input');
let sum = 0;
ele.forEach(input => {
sum += input.value ? parseFloat(input.value) : 0;
});
sum = sum - ele[ele.length - 1].value;
document.getElementById('result').textContent = sum.toFixed(2);
document.getElementById("rowrow").deleteRow(-1);
};
}
function myFunction() {
debugger
var ele = document.querySelectorAll('input.input');
let sum = 0;
ele.forEach(input => {
sum += input.value ? parseFloat(input.value) : 0;
$(input).parents("tr").find(".gst").text((input.value * 0.07).toFixed(2));
});
document.getElementById('result').textContent = sum.toFixed(2);
//document.getElementById('gst').textContent = (sum * 0.07).toFixed(2);
}
.css-serial {
counter-reset: serial-number;
}
.css-serial td:first-child:before {
counter-increment: serial-number;
content: counter(serial-number);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="container">
<div id="body">
<br>
<div class="row">
<div class="css-serial" style="overflow-x:auto;">
<table id="rowrow">
<tr>
<td id="number"></td>
<td><output class="gst">0.00</output></td>
<td><input type="text" name="Amount[]" class="input" oninput="myFunction(this.value)" id="columninput" placeholder="Amount" style="font-size:14px;" min="0" lang="en-150" onchange="force2decimals(this)" onkeypress='validate(event)' inputmode='numeric'
required></td>
Total Amount <output id="result"> 0.00 </output>
<input type="button" id="slipbutton1" onclick="mFunction();" name='add' value="+" />
<input type="button" id="slipbutton2" onclick="remove();" name='remove' value="-" /><br><br>
</table>
</div>
</div>
<br>
</div>
</div>
How could I get the Final Total based on the sum of a checkbox value and the contents of a textbox?
JSFiddle example
My HTML:
<table border="1">
<tr><td>10<input type="checkbox" class="tot_amount" value="10"></td><td>10<input id="os1" type="text"></td></tr>
<tr><td>20<input type="checkbox" class="tot_amount" value="20"></td><td>20<input id="os2" type="text" ></td></tr>
<tr><td>Total<input type="text" id="total1" readonly></td><td>Total2<input id="total2" type="text" readonly></td></tr>
</table>
Final Total<input type="text" id="final" readonly >
And Javascript:
$(".tot_amount").click(function(event) {
var total = 0;
$(".tot_amount:checked").each(function() {
total += parseInt($(this).val());
});
if (total == 0) {
$('#total1').val('');
}
else {
$('#total1').val(total);
}
});
$('#os1, #os2').on('input',function(){
var os1= parseFloat($('#os1').val()) || 0;
var os2= parseFloat($('#os2').val()) || 0;
$('#total2').val(os1 + os2);
});
Just bind a focus event and do it -
$('#final').bind('focus',function(){
$(this).val(parseInt($('#total1').val())+parseInt($('#total2').val()));
});
LIVE http://jsfiddle.net/mailmerohit5/h43te3z6/
I have this code:
<script>
/* Set rates + misc */
var taxRate = 0.08;
var shippingRate = 0.00;
var fadeTime = 300;
/* Assign actions */
$('.product-quantity input').change( function() {
updateQuantity(this);
});
$('.product-removal button').click( function() {
removeItem(this);
});
/* Recalculate cart */
function recalculateCart()
{
var subtotal = 0;
/* Sum up row totals */
$('.product').each(function () {
subtotal += parseFloat($(this).children('.product-line-price').text());
});
/* Calculate totals */
var tax = subtotal * taxRate;
var shipping = (subtotal > 0 ? shippingRate : 0);
var total = subtotal + tax + shipping;
/* Update totals display */
$('.totals-value').fadeOut(fadeTime, function() {
$('#cart-subtotal').html(subtotal.toFixed(2));
$('#cart-tax').html(tax.toFixed(2));
$('#cart-shipping').html(shipping.toFixed(2));
$('#cart-total').html(total.toFixed(2));
if(total == 0){
$('.checkout').fadeOut(fadeTime);
}else{
$('.checkout').fadeIn(fadeTime);
}
$('.totals-value').fadeIn(fadeTime);
});
}
/* Update quantity */
function updateQuantity(quantityInput)
{
/* Calculate line price */
var productRow = $(quantityInput).parent().parent();
var price = parseFloat(productRow.children('.product-price').text());
var quantity = $(quantityInput).val();
var linePrice = price * quantity;
/* Update line price display and recalc cart totals */
productRow.children('.product-line-price').each(function () {
$(this).fadeOut(fadeTime, function() {
$(this).text(linePrice.toFixed(2));
recalculateCart();
$(this).fadeIn(fadeTime);
});
});
}
/* Remove item from cart */
function removeItem(removeButton)
{
/* Remove row from DOM and recalc cart total */
var productRow = $(removeButton).parent().parent();
productRow.slideUp(fadeTime, function() {
productRow.remove();
recalculateCart();
});
}
//# sourceURL=pen.js
</script>
The full demo can watch here:
http://codepen.io/justinklemm/pen/zAdoJ
¿As I can pay by paypal with jquery checkout button?
Example.
Pay Total: $ 90.57 with Paypal
My code button paypal:
<input class="checkout" type="image" src="https://www.paypal.com/en_US/i/btn/btn_xpressCheckout.gif" border="0" name="submit" style="vertical-align:middle" alt="PayPal">
Thanks.
maybe this can help, try playing around with it.
<SCRIPT TYPE="text/javascript">
function MM_goToURL() { //v3.0
var i, args=MM_goToURL.arguments; document.MM_returnValue = false;
for (i=0; i<(args.length-1); i+=2) eval(args[i]+".location='"+args[i+1]+"'");
}
function Dollar (val) { // force to valid dollar amount
var str,pos,rnd=0;
if (val < .995) rnd = 1; // for old Netscape browsers
str = escape (val*1.0 + 0.005001 + rnd); // float, round, escape
pos = str.indexOf (".");
if (pos > 0) str = str.substring (rnd, pos + 3);
return str;
}
function ReadForm (obj1) { // process un-named selects
var i,j,amt,des,obj,pos,tok,val;
var ary = new Array ();
amt = obj1.baseamt.value*1.0; // base amount
des = obj1.basedes.value; // base description
for (i=0; i<obj1.length; i++) { // run entire form
obj = obj1.elements[i]; // a form element
if (obj.type == "select-one" && // just get selects
obj.name == "") { // must be un-named
pos = obj.selectedIndex; // which option selected
val = obj.options[pos].value; // selected value
ary = val.split (" "); // break apart
for (j=0; j<ary.length; j++) { // look at all items
// first we do single character tokens...
if (ary[j].length < 2) continue;
tok = ary[j].substring (0,1); // first character
val = ary[j].substring (1); // get data
if (tok == "#") amt = val * 1.0;
if (tok == "+") amt = amt + val*1.0;
if (tok == "%") amt = amt + (amt * val/100.0);
if (tok == "#") { // record item number
if (obj1.item_number) obj1.item_number.value = val;
ary[j] = ""; // zap this array element
}
// Now we do 3-character tokens...
if (ary[j].length < 4) continue;
tok = ary[j].substring (0,3); // first 3 chars
val = ary[j].substring (3); // get data
if (tok == "s1=") { // value for shipping
if (obj1.shipping) obj1.shipping.value = val;
ary[j] = ""; // clear it out
}
if (tok == "s2=") { // value for shipping2
if (obj1.shipping2) obj1.shipping2.value = val;
ary[j] = ""; // clear it out
}
}
val = ary.join (" "); // rebuild val with what's left
if (des.length == 0) des = val; // 1st storage?
else des = des + ", " + val; // nope, accumulate value
}
}
obj1.item_name.value = des;
obj1.amount.value = Dollar (amt);
if (obj1.tot) obj1.tot.value = "$" + Dollar (amt);
}
</SCRIPT>
<FORM id=viewcart name=viewcart action=https://www.paypal.com/cgi-bin/webscr
method=post>
</FORM>
<FORM onSubmit="this.target = 'paypal';
ReadForm (this.form);"
action=https://www.paypal.com/cgi-bin/webscr method=post>
<P>
<INPUT type=hidden value=_cart name=cmd>
<INPUT type=hidden value=1 name=add>
<INPUT type=hidden value=my#email.com name=business>
<INPUT type=hidden name=item_name>
<INPUT type=hidden name=item_number>
<INPUT type=hidden name=amount>
<INPUT type=hidden value=USD name=currency_code>
<INPUT type=hidden value=USD name=lc>
<INPUT type=hidden value=00 name=shipping>
<INPUT type=hidden value=00.00 name=baseamt>
<INPUT type=hidden VALUE="itemname" name=basedes>
<INPUT TYPE="hidden" NAME="on0" VALUE="Details">
<INPUT TYPE="hidden" NAME="os0" VALUE="moredetails" MAXLENGTH="800">
<BR>
<BR>
</P>
<TABLE WIDTH="400px" BORDER="0" CELLPADDING="0" CELLSPACING="0" align="right">
<TR>
<TD ALIGN="left">
<p class="heading"> </p>
<p class="main"> dropdown1</p>
<p class="heading"> </p>
</TD>
<TD>
<SELECT STYLE="WIDTH: 240px" onChange="ReadForm (this.form);">
<OPTION selected>Please select </OPTION>
<OPTION VALUE="option1 +125.00">option1</OPTION>
<OPTION VALUE="option2 +90.00">option2</OPTION>
<OPTION VALUE="option3 +40.00">option3</OPTION>
</SELECT>
</TD>
</TR>
<TR>
<TD ALIGN="left">
<p class="heading"> </p>
<p class="main"> dropdown2</p>
<p class="heading"> </p>
</TD>
<TD>
<SELECT STYLE="WIDTH: 240px" onChange="ReadForm (this.form);">
<OPTION selected>Please select </OPTION>
<OPTION VALUE="option1 +55.00">option1</OPTION>
<OPTION VALUE="option2 +99.00">option2</OPTION>
<OPTION VALUE="option3 +44.00">option3</OPTION>
</SELECT>
</TD>
</TR>
<tr>
<TR>
<TD ALIGN="left">
<p class="main"> </p>
<p class="main"> Price</p>
<p class="main"> </p>
</TD>
<TD ALIGN="left">
<INPUT class=nbor size=8 value=00.00 name=tot>
</TD>
</TR>
<TD align="left">
<label for="submit"></label>
<TD align="left">
<input type="image" src="/addtocart2.png" name="submit" id="submit" value="submit" >
</div>
</div></td>
</tr>
</table>
</table>
</form>
</TABLE>
</FORM>
</div>
The code I'm playing around with is...
<!DOCTYPE html>
<html>
<body>
<script>
function changeCell(td)
{
var node = td;
while ( (node = node.parentNode) != null )
{
if ( node.tagName == "TD" )
{
node.style.backgroundColor = td.checked ? "red" : "white";
return;
}
}
// not found...give up?
}
</script>
<style>
td { background-color: white; }
</style>
<form name="gradebook">
<table>
<tr>
<td><span id="add_remove">Remove from Calculation:</span></td> <td><input id="pts_earned_1" onclick="changeCell(this);clickCh(this);clickCh_total_pts(this.form.total_pts_1);this.form.total_pts_1.checked = this.checked;" type="checkbox" value="10"> 10 / <span style="display: none"><input id="total_pts_1" type="checkbox" onclick="clickCh_total_pts(this);" value="12"></span> 12<br> </td>
</tr>
<tr>
<td><span id="add_remove">Remove from Calculation:</span></td> <td><input id="pts_earned_2" onclick="changeCell(this);clickCh(this);clickCh_total_pts(this.form.total_pts_2);this.form.total_pts_2.checked = this.checked;" type="checkbox" value="12.5"> 12.5 / <span style="display: none"><input id="total_pts_2" type="checkbox" onclick="clickCh_total_pts(this);" value="14"></span> 14<br></td>
</tr>
</table>
<br>
<input id="pts_earned_total" type="hidden" value="22.5">
<input id="total_pts" type="hidden" value="26">
<div id="pts_earned_display">Pts. Earned: echo the initial pts. earned</div>
<div id="total_pts_display">Total Pts.: echo the initial total pts.</div>
<div id="percentage">Overall Percentage.: echo the initial percent</div>
</form>
<script type="text/javascript">
function clickCh(caller) {
var pts_earned = document.getElementById("pts_earned_total").value*1;
if(caller.checked){ pts_earned -= caller.value*1; }
else { pts_earned += caller.value*1; }
document.getElementById('pts_earned_total').value = pts_earned;
document.getElementById('pts_earned_display').innerHTML = 'Pts. Earned: '+pts_earned.toFixed(2);
}
function clickCh_total_pts(caller) {
var pts_earned = document.getElementById("pts_earned_total").value*1;
var total_pts = document.getElementById("total_pts").value*1;
if(caller.checked){ total_pts += caller.value*1;
document.getElementById('add_remove').innerHTML = 'Remove from Calculation:';
}
else { total_pts -= caller.value*1;
document.getElementById('add_remove').innerHTML = 'Add to Calculation:';
}
document.getElementById('total_pts').value = total_pts;
document.getElementById('total_pts_display').innerHTML = 'Total Pts.: '+total_pts.toFixed(2);
document.getElementById('percentage').innerHTML = 'Overall Percentage: '+Math.round((pts_earned/total_pts)*100*10)/10+'%';
}
</script>
</body>
</html>
When the checkbox is checked, I want the text to toggle between "Remove from Calculation:"and "Add to Calculation:" for the checkbox in the row that was just clicked.
Any thoughts on how to do this? Thanks!
On the checkboxes try using onchange not onclick.
Check out the below, the problem was using the same id twice. It would grab the first use of it. So I changed the id add_remove to add_remove_1 and add_remove_2. Then modified the js to use the caller id to figure out which one to reference.
<!DOCTYPE html>
<html>
<body>
<script>
function changeCell(td) {
var node = td;
while ((node = node.parentNode) != null) {
if (node.tagName == "TD") {
node.style.backgroundColor = td.checked ? "red" : "white";
return;
}
}
// not found...give up?
}
</script>
<style>
td { background-color: white; }
</style>
<form name="gradebook">
<table>
<tr>
<td><span id="add_remove_1">Remove from Calculation:</span></td> <td><input id="pts_earned_1" onclick="changeCell(this);clickCh(this);clickCh_total_pts(this.form.total_pts_1);this.form.total_pts_1.checked = this.checked;" type="checkbox" value="10"> 10 / <span style="display: none"><input id="total_pts_1" type="checkbox" onchange="clickCh_total_pts(this);" value="12"></span> 12<br> </td>
</tr>
<tr>
<td><span id="add_remove_2">Remove from Calculation:</span></td> <td><input id="pts_earned_2" onclick="changeCell(this);clickCh(this);clickCh_total_pts(this.form.total_pts_2);this.form.total_pts_2.checked = this.checked;" type="checkbox" value="12.5"> 12.5 / <span style="display: none"><input id="total_pts_2" type="checkbox" onchange="clickCh_total_pts(this);" value="14"></span> 14<br></td>
</tr>
</table>
<br>
<input id="pts_earned_total" type="hidden" value="22.5">
<input id="total_pts" type="hidden" value="26">
<div id="pts_earned_display">Pts. Earned: echo the initial pts. earned</div>
<div id="total_pts_display">Total Pts.: echo the initial total pts.</div>
<div id="percentage">Overall Percentage.: echo the initial percent</div>
</form>
<script type="text/javascript">
function clickCh(caller) {
var pts_earned = document.getElementById("pts_earned_total").value * 1;
if (caller.checked) { pts_earned -= caller.value * 1; }
else { pts_earned += caller.value * 1; }
document.getElementById('pts_earned_total').value = pts_earned;
document.getElementById('pts_earned_display').innerHTML = 'Pts. Earned: ' + pts_earned.toFixed(2);
}
function clickCh_total_pts(caller) {
var addRemoveId = caller.id.replace("total_pts", "add_remove");
var pts_earned = document.getElementById("pts_earned_total").value * 1;
var total_pts = document.getElementById("total_pts").value * 1;
if (caller.checked) {
total_pts += caller.value * 1;
document.getElementById(addRemoveId).innerHTML = 'Remove from Calculation:';
} else {
total_pts -= caller.value * 1;
document.getElementById(addRemoveId).innerHTML = 'Add to Calculation:';
}
document.getElementById('total_pts').value = total_pts;
document.getElementById('total_pts_display').innerHTML = 'Total Pts.: ' + total_pts.toFixed(2);
document.getElementById('percentage').innerHTML = 'Overall Percentage: ' + Math.round((pts_earned / total_pts) * 100 * 10) / 10 + '%';
}
</script>
</body>