Paypal button and checkout with jquery - javascript

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>

Related

I am having trouble getting a select tag to print one of the two options to a table and then calculate if one of them is selected to add to a total

The program I am trying to write is a pizza ordering program and the majority of it already works, but for my two selection options I want to have the value of one of the options print to the screen and then if the delivery option is selected to add 2 to the total.
Here is what I am using currently for the selection.
function getPizza(){
var price = 0;
var size = "";
var top = 0;
var total = 0;
var select_price = 0;
var select_option = "";
var s1 = document.getElementById("s1");
var s2 = document.getElementById("s2");
var s3 = document.getElementById("s3");
var s4 = document.getElementById("s4");
if(s1.checked==true)
{
price = 8.00;
size = "Small";
}
else if(s2.checked==true)
{
price = 10.00;
size = "Medium";
}
else if(s3.checked==true)
{
price = 12.00;
size = "Large";
}
else if(s4.checked==true)
{
price = 14.00;
size = "X-Large";
}
else
alert("No size selected");
document.getElementById("p_result").innerHTML = "$" + price;
document.getElementById("s_result").innerHTML = size;
var t1 = document.forms["order"]["topping1"].checked;
var t2 = document.forms["order"]["topping2"].checked;
var t3 = document.forms["order"]["topping3"].checked;
var t4 = document.forms["order"]["topping4"].checked;
var t5 = document.forms["order"]["topping5"].checked;
document.getElementById("t_options").innerHTML = '';
if(t1 == true) {
top = top + 1.5;
document.getElementById("t_options").innerHTML += "Pepperoni" + "</br>";
}
if(t2 == true) {
top = top + 1.5;
document.getElementById("t_options").innerHTML += "Sausage" + "</br>";
}
if(t3 == true) {
top = top + 1.5;
document.getElementById("t_options").innerHTML += "Bacon" + "</br>";
}
if(t4 == true) {
top = top + 1.5;
document.getElementById("t_options").innerHTML += "Onions" + "</br>";
}
if(t5 == true) {
top = top + 1.5;
document.getElementById("t_options").innerHTML += "Spinach" + "</br>";
}
document.getElementById("t_result").innerHTML = "$ " + top;
//if structure I thought would work for adding to total.
if (select_option == true)
select_price = select_price + 2;
document.getElementById("sel_opt").innerHTML = select_option;
document.getElementById("sel_price").innerHTML = select_price;
total = total + price + top + select_price;
document.getElementById("total_result").innerHTML = "Your Current Total is $ " + total;
HTML
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<style>
table, th, td {
border:1px solid black;
}
</style>
<body>
<h1>Pizza Program </h1>
<form id="order" name="order">
<label for="first_last"> Name:</label>
<input type="text" name="first_last" id="first_last" placeholder="First Last"> <br>
<p> Please choose your size of pizza:</p>
<input type="radio" name="size" id="s1" value="Small"> Small - $8</input><br>
<input type="radio" name="size" id="s2" value="Medium"> Medium - $10</input><br>
<input type="radio" name="size" id="s3" value="Large"> Large - $12</input><br>
<input type="radio" name="size" id="s4" value="X-Large"> Extra Large - $14</input><br>
<p>Please choose your topping ($1.50 each): </p>
<input type="checkbox" name="topping1" id="topping1" value="pepperoni"> Pepperoni </input><br>
<input type="checkbox" name="topping2" id="topping2" value="sausage"> Sausage </input><br>
<input type="checkbox" name="topping3" id="topping3" value="bacon"> Bacon </input><br>
<input type="checkbox" name="topping4" id="topping4" value="onions"> Onions </input><br>
<input type="checkbox" name="topping5" id="topping5" value="spinach"> Spinach </input><br> <br>
<select name="pick_deliv" id="select1">
<option id="pick_up" value="Pickup">Pick up</option>
<option id="deliv" value="Delivery">Delivery</option>
</select> <br> <br>
</form>
<button onclick="getPizza()" id="btn1"> Confirm Order</button>
<h1 id="name_result"> Your Order </h1> <br> <br>
<table style="width:50%">
<tr>
<th>Description</th>
<th>Option</th>
<th>Price</th>
</tr>
<tr>
<td> Size </td>
<td id="s_result"> </td>
<td id="p_result"> </td>
</tr>
<tr>
<td> Toppings </td>
<td id="t_options"> </td>
<td id="t_result"> </td>
</tr>
<tr>
<td> Pick-Up/Delivery</td>
<td id="sel_opt"> </td>
<td id="sel_price"> </td>
</tr>
</table>
<h4 id="total_result">Your Current Total is $ </h4>
<p id="demo"> </p>
</body>
</html>

Jquery Hide Div element if length greater then

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();
}
});

Javascript not working to validate or give total on a sample order form

Ok I created a javascript for a simple HTML form to validate as well as give you a popup of the total or if anything is wrong with one of the inputs.
heres the javascript
function processOrderform() {
var OrderFormObj = document.getElementById("OrderForm");
if (validateInput(OrderFormObj)) {
var total = calculateTotal(OrderFormObj);
alert("Your Total Is: $" + total + ". Thank you for your order! We hope to see you again!");
}
}
function validateInput(OrderFormObj) {
var product1_prices = OrderFormObj.product1.options[OrderFormObj.product1.selectedIndex].value;
var product2_prices = OrderFormObj.product2.options[OrderFormObj.product2.selectedIndex].value;
var product3_prices = OrderFormObj.product3.options[OrderFormObj.product3.selectedIndex].value;
var product4_prices = OrderFormObj.product4.options[OrderFormObj.product4.selectedIndex].value;
var quantity1 = OrderFormObj.quantity1.value;
var quantity2 = OrderFormObj.quantity2.value;
var quantity3 = OrderFormObj.quantity3.value;
var quantity4 = OrderFormObj.quantity4.value;
var taxexempt = OrderFormObj.taxexempt.value;
var quantity1OK, quantity2OK, quantity3OK, quantity4OK, taxexemptOK;
quantity1OK = validateQuantity1(quantity1);
quantity2OK = validateQuantity2(quantity2);
quantity3OK = validateQuantity3(quantity3);
quantity4OK = validateQuantity4(quantity4);
taxexemptOK = validateTaxExempt;
if (OrderFormObj.tax.checked) {
taxexemptOK = validateTaxExempt(taxexempt);
}
return quantity1OK && quantity2OK && emailOK && taxexemptOK;
}
function validateQuantity1(quantity1) {
if (isNaN(quantity1)) {
alert("Error: Please input a number for processor quantity.")
return false;
}
if (quantity1 < 0 || quantity1 > 50) {
alert("Error: The maximum quantity of processors you can order is 50. Please select a smaller amount or contact us for more information.")
return false;
}
return true;
}
function validateQuantity2(quantity2) {
if (isNaN(quantity2)) {
alert("Error: Please input a number for storage drive quantity.")
return false;
}
if (quantity2 < 0 || quantity2 > 50) {
alert("Error: The maximum quantity of storage drives you can order is 50. Please select a smaller amount or contact us for more information.")
return false;
}
return true;
}
function validateQuantity3(quantity3) {
if (isNaN(quantity3)) {
alert("Error: Please input a number for memory quantity.")
return false;
}
if (quantity3 < 0 || quantity3 > 50) {
alert("Error: The maximum quantity of memory you can order is 50. Please select a smaller amount or contact us for more information.")
return false;
}
return true;
}
function validateQuantity4(quantity4) {
if (isNaN(quantity4)) {
alert("Error: Please input a number for graphics card quantity.")
return false;
}
if (quantity4 < 0 || quantity4 > 50) {
alert("Error: The maximum quantity of graphics cards you can order is 50. Please select a smaller amount or contact us for more information.")
return false;
}
return true;
}
function validateTaxExempt(taxexempt) {
var p = taxexempt.search(/^\d{8}$/);
if (p == 0)
return true;
else {
alert("Error: Invalid tax-exempt code. Please enter an 8-digit code.");
return false;
}
}
function calculateTotal(OrderFormObj) {
var product1_prices = OrderFormObj.product1.options[OrderFormObj.product1.selectedIndex].value;
alert("Processor Price is $" + product1_prices);
var quantity1 = OrderFormObj.quantity1.value;
alert("Your processor quantity is " + quantity1);
var product2_prices = OrderFormObj.product2.options[OrderFormObj.product2.selectedIndex].value;
alert("Storage Drive Price is $" + product2_prices);
var quantity2 = OrderFormObj.quantity2.value;
alert("Your storage drive quantity is " + quantity2);
var product3_prices = OrderFormObj.product3.options[OrderFormObj.product3.selectedIndex].value;
alert("Memory price is $" + product3_prices);
var quantity3 = OrderFormObj.quantity3.value;
alert("Your memory quantity is " + quantity3);
var product4_prices = OrderFormObj.product4.options[OrderFormObj.product4.selectedIndex].value;
alert("Graphics Card price is $" + product4_prices);
var quantity4 = OrderFormObj.quantity4.value;
alert("Your graphics card quantity is " + quantity4);
var taxexempt = OrderFormObj.taxexempt.value;
alert("Your tax exempt code is " + taxexempt);
var quantity1OK, quantity2OK, quantity3OK, quantity4OK, taxexemptOK;
var checkboxs = OrderFormObj.service;
for (var i = 0; i < checkbox.length; i++) {
if (checkboxs[i].checked) {
var services_prices = checkbox[i].value;
break;
}
}
var getProduct1Price = parseFloat(product1_prices) * parseFloat(quantity1);
var getProduct2Price = parseFloat(product2_prices) * parseFloat(quantity2);
var getProduct3Price = parseFloat(product3_prices) * parseFloat(quantity3);
var getProduct4Price = parseFloat(product4_prices) * parseFloat(quantity4);
var service_price = parseFloat(document.getElementById('service').value);
var total = getProduct1Price + getProduct2Price + getProduct3Price + getProduct4Price + service_price;
return total;
}
and heres the html for it
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- bmi5.html -->
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script type="text/javascript" src="orderscript.js">
</script>
<title>Products & Services</title>
</head>
<body>
<h1>PC Products</h1>
<form id="OrderForm" method="post" action=""
onsubmit="processOrderform()">
<tr>
<td><label for="product1">Processors:</label></td>
<td><select id="product1" name="product1">
<option>Select Device</option>
<option value="139.99">Intel i3 - $140</option>
<option value="189.99">Intel i5 - $190</option>
<option value="239.99">Intel i7 - $240</option>
</select></td>
<td><label for="quantity1">Quantity :</label></td>
<td><input id="quantity1" type="text" name="quantity1" size ="1" /></td>
</tr><br />
<tr>
<td><label for="product2">Storage:</label></td>
<td><select id="product2" name="product2"></td>
<td><option>Select Device</option>
<option value="149.99">SSD 128GB - $149.99</option>
<option value="249.99">SSD 256GB - $249.99</option>
<option value="519.00">SSD 512GB - $519.00</option>
<option value="69.99">HDD 500GB - $69.99</option>
<option value="109.99">HDD 1TB - $109.99</option>
<option value="149.99">HDD 1.5TB - $149.99</option>
<option value="199.99">HDD 3TB - $199.99</option>
</select></td>
<td><label for="quantity2">Quantity :</label></td>
<td><input id="quantity2" type="text" name="quantity2" size ="1"></td>
</tr><br />
<tr>
<td><label for="product3">Memory:</label></td>
<td><select id="product3" name="product3"></td>
<td><option>Select Device</option>
<option value="59.99">DDR3 8GB - $59.99</option>
<option value="109.99">DDR3 16GB - $109.99</option>
<option value="209.99">DDR3 32GB - $209.99</option>
</select></td>
<td><label for="quantity3">Quantity :</label></td>
<td><input id="quantity3" type="text" name="quantity3" size ="1"></td>
</tr><br />
<tr>
<td><label for="product4">Graphics Card:</label></td>
<td><select id="product4" name="product4"></td>
<td><option>Select Device</option>
<option value="139.99">Nvidia - $649.99</option>
<option value="189.99">AMD - $449.99</option>
</select></td>
<td><label for="quantity4">Quantity :</label></td>
<td><input id="quantity4" type="text" name="quantity4" size ="1"></td>
</tr><br />
<br />
<table> Service and Repair
<tr><td><input id="virus" type="checkbox" name="service" value="99.99"></td>
<td>Virus Removal</td> <td align="right"><tt>99.99</tt></td></tr>
<tr><td><input id="lesson" type="checkbox" name="service" value="29.99"></td>
<td>1 Hour Computer Lessons</td> <td align="right"><tt>29.99</tt></td></tr>
<tr><td><input id="assembly" type="checkbox" name="service" value=49.99"></td>
<td>PC Assembly</td> <td align="right"><tt>49.99</tt></td></tr>
</table>
<br />
<h4><i>*Sales Tax of 8.25% applies</i></h4>
<td>Tax exempt check box:
<input type="checkbox" name="reply" value="yes" /><br /></td>
<p>
<input type="hidden" id="itemname" name = "itemname" value= "">
<td><input type="submit" value="Submit your order" /></td>
<td><input type="reset" value="Reset form" /></td>
</p>
</form>
</body>
</html>
any input would be great.
If you are accessing some form element with its 'id' then it is not required to use form id also with them. You can simply access the form elements like this:
var product1 = document.getElementById('product1').value;
If you want to access the form elements with their names then you have to use form name too. Assuming your form name is 'OrderForm', It will be like this:
document.forms['OrderForm']['product1'].value;
These things you have to correct in your javascript part. Secondly, you have used some codes like:
var quantity1 = OrderFormObj.quantity1.value;
This also needs to be corrected. If you want quantity1 field value, you can simply get it like this:
var quantity1 = document.getElementById('quantity1').value;

Using radio buttons within javascript for a calculation

I've been working at this for a few hours and I cannot, for the life of my figure out how to do this.
So, I wanted to make a calculation in java-script (on the back of HTML). And I was wondering how I could get the radio button to chance the value of a number of vars. E.G (female radio button checked, var a = 10, var x = 20, etc..., but if male radio button checked, var a = 34,var x = 32, etc...)
also along with this I wanted to know if i could do a long sum like for example (bmr = a + (x * weight) + (y * height) - (z * age)). Then finally diplay all this information on a different text field.
HTML
<!DOCTYPE html PUBLIC>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<SCRIPT type="text/javascript" src="jstest.js">
</SCRIPT>
</head>
<body>
<form action="" method="post" name="caloriecalc">
<table>
<tr>
<td>Age:</td>
<td>
<input type="text" name="age" size="5" />
</td>
</tr>
<tr>
<td>Gender:</td>
<td>
<label>
<input type="radio" name="gender" value="male" />Male</label>
<br />
<label>
<input type="radio" name="gender" value="female" />Female</label>
<br />
</td>
</tr>
<tr>
<td>Weight:</td>
<td>
<input type="text" name="weight" size="7" />KG</td>
</tr>
<tr>
<td>Height:</td>
<td>
<input type="text" name="height" size="7" />CM</td>
</tr>
<tr>
<td>
<label>Exercise Level:</label>
</td>
<td>
<select name="activity">
<option value="1.2">Sedentary (little or no exercise)</option>
<option value="1.375">Lightly active (exercise/sports 1-3 days/wk</option>
<option value="1.55">Mod. active (exercise/sports 3-5 days/wk)</option>
<option value="1.725">Very active (exercise/sports 6-7 days/wk)</option>
<option value="1.9">Extr. Active (daily exercise/sports & physical job))</option>
</select>
</td>
</tr>
<tr>
<td></td>
<td>
<input name="calc" type="button" value="Calculate" onclick="validate()" />
</td>
</tr>
<tr>
</table>
</form>
<table width="100%">
<tr>
<td width="50%" align="right">BMR</td>
<td width="50%" id="bmr"></td>
</tr>
</table>
</body>
</html>
JAVASCRIPT
function validate() {
var age = document.caloriecalc.age.value;
var weight = document.caloriecalc.weight.value;
var height = document.caloriecalc.height.value;
if (age <= 0 || parseInt(age) != age) {
alert("Please enter a valid age.");
} else if (weight <= 0 || isNaN(Number(weight))) {
alert("Please enter a valid weight.");
} else if (height <= 0 || isNaN(Number(height))) {
alert("Please enter a valid height.");
} else { //all the data has been validated
calculate(parseInt(age), parseFloat(weight), parseFloat(height));
}
}
function calculate(age, weight, height) {
}
Try something like
function validate() {
var i , gender;
var age = document.caloriecalc.age.value;
var weight = document.caloriecalc.weight.value;
var height = document.caloriecalc.height.value;
for(i = 0; i < document.caloriecalc.gender.length; i++){
if(document.caloriecalc.gender[i].checked){
gender = document.caloriecalc.gender[i].value;
}
}
if (age <= 0 || parseInt(age) != age) {
alert("Please enter a valid age.");
} else if (!gender) {
alert("Please enter a valid gender.");
} else if (weight <= 0 || isNaN(Number(weight))) {
alert("Please enter a valid weight.");
} else if (height <= 0 || isNaN(Number(height))) {
alert("Please enter a valid height.");
} else { //all the data has been validated
calculate(parseInt(age), parseFloat(weight), parseFloat(height), gender);
}
}
function calculate(age, weight, height, gender) {
var a, x, y = 1, z = 1;
switch(gender){
case "male":
a= 34;
x =32;
break;
case "female":
a= 10;
x =20;
break;
}
var bmr = a + (x * weight) + (y * height) - (z * age);
document.getElementById('bmr').innerHTML = bmr;
}
Demo: Fiddle
Note: I don't know the value for y and z as you haven't mentioned them
You can get the value of radio button by using :-
var lengthh=document.caloriecalc.gender.length;
for(var i=0;i<lengthh;i++){
if(document.caloriecalc.gender[i].checked){
gender = document.caloriecalc.gender[i].value;
}
}
Now pass the values to calculate function and do you calculation as below :-
function calculate(age, weight, height, gender) {
var a=0, x=0, y = 1, z = 1;
if(gender=='male'){
a= 34;
x =32;
}else{
a= 10;
x =20;
}
//Now the result is
var resultt = a + (x * weight) + (y * height) - (z * age);
document.getElementById('bmr').innerHTML = resultt;
}
Hope it will help you.

Toggle text when checkbox is checked/unchecked

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>

Categories