Drop-down for discount calculation in javascript - javascript

I tried to get gross total value from discount calculation to sub total value.
Below is my code:
HTML/PHP
<select class="select" id="discount" onchange="discountedGrossTotal()">
<option selected>0</option>
<option value=".02">2</option>
<option value=".03">3</option>
<option value=".04">4</option>
</select> </td>
<input name="txtGrossTotal" type="text" id="txtGrossTotal" size="15" readonly/>
<input name="txtSubTotal" type="text" id="txtSubTotal" size="15" value="<?php $sql=mysqli_query($connection,'select sum(amount) from sales_temp');
$row = mysqli_fetch_array($sql);
echo $row[0]; ?>"/>
Javascript
function discountedGrossTotal(){
var discountOption = document.getElementById("discount"),
subTotal = document.getElementById("txtSubTotal"),
grossTotal = document.getElementById("txtGrossTotal");
discountOption.addEventListener('change', function (e) {
grossTotal.value = subTotal - subTotal * this[this.selectedIndex].value;
});
}
When selects the first option of the drop down, it displays nothing in the Gross Total text box. From then, it displays as "NaN" in the text box, whatever option selects.
Appreciate your help on this.

function discountedGrossTotal(dropdownVal){
var discountOption = document.getElementById("discount"),
subTotal = document.getElementById("txtSubTotal"),
grossTotal = document.getElementById("txtGrossTotal");
grossTotal.value = subTotal.value - (subTotal.value * dropdownVal);
}
<select class="select" id="discount" onchange="discountedGrossTotal(this.value)">
<option value="0">0</option>
<option value=".02">2</option>
<option value=".03">3</option>
<option value=".04">4</option>
</select>
<input name="txtGrossTotal" type="text" id="txtGrossTotal" size="15" value="" readonly/>
<input name="txtSubTotal" type="text" id="txtSubTotal" size="15" value="200"/>

I would suggest either way to do this:
HTML/PHP
<select class="select" id="discount">
<option selected>0</option>
<option value=".02">2</option>
<option value=".03">3</option>
<option value=".04">4</option>
</select> </td>
<input name="txtGrossTotal" type="text" id="txtGrossTotal" size="15" readonly/>
<input name="txtSubTotal" type="text" id="txtSubTotal" size="15" value="<?php $sql=mysqli_query($connection,'select sum(amount) from sales_temp');
$row = mysqli_fetch_array($sql);
echo $row[0]; ?>"/>
Javascript
var discountOption = document.getElementById("discount");
discountOption.addEventListener('change', function (e) {
var dropdownVal = document.getElementById("discount").value;;
var subTotal = document.getElementById("txtSubTotal").value;
var grossTotal = document.getElementById("txtGrossTotal").value;
grossTotal.value = (subTotal) - (subTotal * dropdownVal);
});
}

Related

How to get the second value in the id to make onchange function?

I want to get the quantity value on change to show in the input, I make it data-cat_id='{$quantity}' to show, but it cannot work.This value='{$id_book}' is cannot change to '{$quantity}', because id_book I want to use other place. Below is my coding:
<label>Choose Book:<span style="color:red;"> *</span></label>
<select class="form-control" id="publisher" name="publisher" title="publisher">
<option value="">Please Select</option>
<?php
$sql_branch = 'select * from book_lending where status=1 order by id';
$arr_branch = db_conn_select($sql_branch);
foreach ($arr_branch as $rs_branch) {
$quantity = $rs_branch['quantity'];
$id_book = $rs_branch['id'];
$book_title = $rs_branch['title'];
//echo '<option value="' . $rs_branch['id'] . '" data-cat_id='{$quantity}'>' . $rs_branch['title'] . '</option>';
echo "<option value='{$id_book}' data-cat_id='{$quantity}'>{$book_title}</option>";
}
?>
</select>
<label for="cp1" class="control-label">Book Stock<span style="color:red;"> *</span></label>
<input readonly="readonly" type="text" class="form-control" id="editor" name="editor" title="editor" value="" >
<script>
//let cat_id = selectObject.value;
let cat_id = selectObject.selectedOptions[0].getAttribute("data-cat_id");
$(function(){
$(cat_id).change(function(){
var value=$(cat_id).val();
$("#editor").val(value);
})
})
</script>
Below is my output:
Hope someone can guide me how to show data-cat_id value in the input. Thanks.
I hope I understood correctly that you wish to set the dataset attribute cat_id associated with each option in the text input field when the user changes the dropdown selection?
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title></title>
</head>
<body>
<label>Choose Book:<span style='color:red;'> *</span></label>
<select class='form-control' id='publisher' name='publisher' title='publisher'>
<option selected hidden disabled>Please Select
<?php
# Un-comment the following
/*
$sql_branch = 'select * from book_lending where status=1 order by id';
$arr_branch = db_conn_select( $sql_branch );
*/
#to emulate a recordset...Remove this next piece
$arr_branch=array(
['id'=>1,'quantity'=>2,'title'=>'Top tips'],
['id'=>2,'quantity'=>4,'title'=>'Tip tops'],
['id'=>3,'quantity'=>8,'title'=>'Stop Tip'],
['id'=>5,'quantity'=>16,'title'=>'Pit Stop'],
);
#stop
foreach ( $arr_branch as $rs_branch ) {
printf(
'<option value="%s" data-cat_id="%s">%s',
$rs_branch['id'],
$rs_branch['quantity'],
$rs_branch['title']
);
}
?>
</select>
<label for='cp1' class='control-label'>Book Stock<span style='color:red;'> *</span></label>
<input readonly='readonly' type='text' class='form-control' id='editor' name='editor' title='editor' value='' />
<script>
let oSelect=document.querySelector('select[name="publisher"]');
let oInput=document.querySelector('input[name="editor"]');
oSelect.addEventListener('change',function(e){
oInput.value=this.options[ this.options.selectedIndex ].dataset.cat_id;
});
</script>
</body>
</html>
let oSelect=document.querySelector('select[name="publisher"]');
let oInput=document.querySelector('input[name="editor"]');
oSelect.addEventListener('change',function(e){
oInput.value=this.options[this.options.selectedIndex].dataset.cat_id;
});
<label>Choose Book:<span style='color:red;'> *</span></label>
<select class='form-control' id='publisher' name='publisher' title='publisher'>
<option selected hidden disabled>Please Select
<option value="1" data-cat_id="2">Top tips
<option value="2" data-cat_id="4">Tip tops
<option value="3" data-cat_id="8">Stop Tip
<option value="5" data-cat_id="16">Pit Stop
</select>
<label for='cp1' class='control-label'>Book Stock<span style='color:red;'> *</span></label>
<input readonly='readonly' type='text' class='form-control' id='editor' name='editor' title='editor' value='' />

How to calculate math in form and insert data into text input with javascript?

I have been looking for a solution to this problem for about 3 days with no avail. So I have decided to post a question regarding it.
In this form I am trying to grab data from two form elements figure out a percentage and input that data into a text input and a hidden input element.
HTML
<head><script type="text/javascript" src="vali.js" async></script></head>
<body onload="hideTotal()">
<form class="form-horizontal" id="req_serv" name="req_serv" method="post" action="index.php">
<label>Order Total :</label>
<input class="form-control" id="ordertot" type="number" name="ordertot" placeholder="$0.00" onkeyup="calculateTotal()" />
<span class="error"><?php echo $ordertotError;?></span>
<label>Service & Fee</label>
<select class="form-control" id="servfee" name="servfee" onchange="calculateTotal()">
<option value="none">Select Service</option>
<option value="ref_thou_less">Refunds</option>
<option value="ref_thou_more">Refunds++</option>
<option value="rep_thou_less">Replacements</option>
<option value="rep_thou_more">Replacements++</option>
<option value="dbl_reprep_thou_less">Double Dip</option>
<option value="dbl_reprep_thou_more">Double Dip++</option>
<option value="dbl_repref_thou_less">Double Dip+++</option>
<option value="dbl_repref_thou_more">Double Dip++++</option>
</select>
<br/>
<label>What You Pay: </label>
<input type="number" required="required" id="totalPrice" name="tp">
<input class="submit" type="submit" name="submit" value="Submit">
<span class="success"><?php echo $successMessage;?></span>
</form>
</body>
JS
var service_fee=new Array();
service_fee["none"]=0;
service_fee["ref_thou_less"]=7.5;
service_fee["ref_thou_more"]=12.5;
service_fee["rep_thou_less"]=10;
service_fee["rep_thou_more"]=15;
service_fee["dbl_reprep_thou_less"]=17.5;
service_fee["dbl_reprep_thou_more"]=27.5;
service_fee["dbl_repref_thou_less"]=15;
service_fee["dbl_repref_thou_more"]=25;
//This function finds the service type price based on the
//drop down selection
function getServicePrice()
{
var ServicePrice=0;
//Get a reference to the form id="req_serv"
var theForm = document.forms["req_serv"];
//Get a reference to the select id="servfee"
var selectedservtype = theForm.elements["servfee"];
ServicePrice = service_fee[selectedservtype.value];
//finally we return service price
return ServicePrice;
}
function calculateTotal()
{
//Here we get the total price by calling our function
//Each function returns a number so by calling them we add the values they return together
var reqservfee = getServicePrice() * 100 / getOrderTotal();
//display the result
var txtobj = document.getElementById('totalPrice');
txtobj.style.display='block';
txtobj.value = reqservfee;
}
function hideTotal()
{
var txtobj = document.getElementById('totalPrice');
txtobj.style.display='none';
}
getOrderTotal is not defined in your script
var service_fee = {};
service_fee["none"] = 0;
service_fee["ref_thou_less"] = 7.5;
service_fee["ref_thou_more"] = 12.5;
service_fee["rep_thou_less"] = 10;
service_fee["rep_thou_more"] = 15;
service_fee["dbl_reprep_thou_less"] = 17.5;
service_fee["dbl_reprep_thou_more"] = 27.5;
service_fee["dbl_repref_thou_less"] = 15;
service_fee["dbl_repref_thou_more"] = 25;
function getServicePrice() {
var ServicePrice = 0;
var theForm = document.forms["req_serv"];
var selectedservtype = theForm.elements["servfee"];
ServicePrice = service_fee[selectedservtype.value];
return ServicePrice;
}
function getOrderTotal() {
return document.getElementById('ordertot').value;
}
function calculateTotal() {
var reqservfee = (getServicePrice() / 100) * getOrderTotal();
var txtobj = document.getElementById('totalPrice');
txtobj.style.display = 'block';
txtobj.value = reqservfee;
}
function hideTotal() {
var txtobj = document.getElementById('totalPrice');
txtobj.style.display = 'none';
}
<body onload="hideTotal()">
<form class="form-horizontal" id="req_serv" name="req_serv" method="post" action="index.php">
<label>Order Total :</label>
<input class="form-control" id="ordertot" type="number" name="ordertot" placeholder="$0.00" onkeyup="calculateTotal()" />
<span class="error"><?php echo $ordertotError;?></span>
<label>Service & Fee</label>
<select class="form-control" id="servfee" name="servfee" onchange="calculateTotal()">
<option value="none">Select Service</option>
<option value="ref_thou_less">Refunds</option>
<option value="ref_thou_more">Refunds++</option>
<option value="rep_thou_less">Replacements</option>
<option value="rep_thou_more">Replacements++</option>
<option value="dbl_reprep_thou_less">Double Dip</option>
<option value="dbl_reprep_thou_more">Double Dip++</option>
<option value="dbl_repref_thou_less">Double Dip+++</option>
<option value="dbl_repref_thou_more">Double Dip++++</option>
</select>
<br/>
<label>What You Pay:</label>
<input type="number" required="required" id="totalPrice" name="tp">
<input class="submit" type="submit" name="submit" value="Submit">
<span class="success"><?php echo $successMessage;?></span>
</form>
</body>

Changing Variable in forms onclick

Okay guys... I've built an eCommerce site for my wife, who sells eLiquids.. The problem I am having has to do with the e-junkie cart I'm using... I am trying to change the hidden value of "amount" when a bottle size is selected from a dropdown box.. I would like the "amount" value to change depending on each size selection... nothing i've tried has worked.. here's the snippet
<form action="https://www.e-junkie.com/ecom/fgb.php?c=cart&cl=1&ejc=2" target="ej_ejc" method="POST">
<input type="hidden" name="amount" value="12.00"/>
<input type="hidden" name="quantity" value="1"/>
Bottle Size:
<input type="hidden" name="on1" value="Size"/>
<select name="os1" >
<option value="15">15 ML</option><option value="30">30 ML</option>
<option value="50">50 ML</option>
</select><br>
<input type="hidden" name="shipping2" value="0.5">
<input type="hidden" name="handling" value="0.5">
<input type="hidden" name="tax" value="0.50"/>
<input type="hidden" name="return_url" value="http://www.e-junkie.com/"/>
<input type="hidden" name="currency_code" value="USD"/>
<input type="image" src="https://www.e-junkie.com/ej/ej_add_to_cart.gif" border="0" onClick="javascript:return EJEJC_lc(this.parentNode);">
I've tried using onClick with the on1, but it doesn't change the amount value...
I'm trying to change the hidden "amount" value to either 12 20 or 30 depending on which size is selected... any help would be great
You can change the value of the amount field by assigning an onchange function to the os1 select box. Here is an example javascript function:
function changePrice() {
var size = document.getElementById('os1').value;
var price = 12;
switch(size){
case '15':
price = 12;
break;
case '30':
price = 20;
break;
case '50':
price = 30;
break;
}
document.getElementById('amount').value = price;
}
You would then also need to give you amount input an ID:
<input type="hidden" name="amount" value="12.00" id="amount" />
And give the select box an ID, and assign it an onclick event:
<select name="os1" id="os1" onchange="changePrice();">
<option value="15">15 ML</option>
<option value="30">30 ML</option>
<option value="50">50 ML</option>
</select>
However - I don't recommend doing this if you are dealing with payments. It would be too easy for someone to change the amount value themselves in their browser and submit any amount they want to the payment process. At the very least you need to validate the bottle size and amount to pay on your server before processing the payment to prevent this kind of attack.
This is not nice and raw JavaScript but it should work for you.
Change
<input type="hidden" name="amount" value="12.00"/>
to
<input type="hidden" id="amount" name="amount" value="12.00"/>
And change:
<select name="os1" >
<option value="15">15 ML</option><option value="30">30 ML</option>
<option value="50">50 ML</option>
</select><br>
to
<select id="os1" name="os1" >
<option value="15">15 ML</option><option value="30">30 ML</option>
<option value="50">50 ML</option>
</select><br>
And finally change:
<input type="image" src="https://www.e-junkie.com/ej/ej_add_to_cart.gif" border="0" onClick="javascript:return EJEJC_lc(this.parentNode);">
To
<input type="image" src="https://www.e-junkie.com/ej/ej_add_to_cart.gif" border="0" onClick="return changeCost();">
<script type="text/javascript">
function changeCost(){
var amountElm = document.getElementById("amount");
var selectList = document.getElementById("os1");
var selectedValue = selectList .options[selectList .selectedIndex].value;
if(selectedValue == "15"){
amountElm.value "12.00";
}else if(selectedValue == "30"){
amountElm.value "20.00";
}else if(selectedValue == "50"){
amountElm.value "30.00";
}
return true;
}
</script>

Converting HTML functions into PHP scripts. (two select values to multiply) [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
My job is to convert the following javascript functions into PHP and display the correct results. How do you use PHP to multiply the two values of the NumA and NumB select options? The discount must be displayed in the discount input box, as well as the grand total in the total input box. I am having difficulties creating a PHP script that takes the two selected options's values and multiplies them, while displaying the two results in the boxes below.
This is the HTML code with the functions that I need to convert to PHP.
<!DOCTYPE html>
<html>
<head>
<title>
</title>
<script>
var numA = 0;
function totalA(valA) {
if (valA) {
numA = Number(valA);}
var disc = numB*numA;
var totalCost = (numA - disc);
document.getElementById("total").value = "$" + totalCost.toFixed(2);
document.getElementById("discount").value = "$" + disc.toFixed(2);}
var numB = 0;
function totalB(valB) {
if (valB) {
numB = Number(valB);}
var disc = numB*numA;
var totalCost = (numA - disc);
document.getElementById("total").value = "$" + totalCost.toFixed(2);
document.getElementById("discount").value = "$" + disc.toFixed(2);}
</script>
</head>
<div align="center">
<br>
<form name id="Main">
<select id="numA" placeholder="Please select a service" onchange="totalA(this.value);">
<option value="" disabled selected>Select your service</option>
<option value="125">Makeover</option>
<option value="60">Hair Styling</option>
<option value="35">Manicure</option>
<option value="200">Permanent Makeup</option>
</select>
<br><br>
<select id="NumB" placeholder="Please select the discount" onchange="totalB(this.value);">
<option value="" disabled selected>Select the discount</option>
<option value="0">0%</option>
<option value=".1">10%</option>
<option value=".2">20%</option>
</select>
<br><br>
<td>Discount Coupon: <input id="discount" name="showTotal" type="text" value="$0.00" size="10" readonly/></td>
<td>Grand Total: <input id="total" name="showTotal" type="text" value="$0.00" size="10" readonly=""/></td>
<br><br>
</form>
<hr>
</div>
</html>
First update your form:
<form action="" method="post">
<select name="service" id="service" placeholder="Please select a service">
<option value="" disabled selected>Select your service</option>
<option value="125">Makeover</option>
<option value="60">Hair Styling</option>
<option value="35">Manicure</option>
<option value="200">Permanent Makeup</option>
</select>
<br><br>
<select name="discount" id="discount" placeholder="Please select the discount">
<option value="" disabled selected>Select the discount</option>
<option value="0">0%</option>
<option value=".1">10%</option>
<option value=".2">20%</option>
</select>
<br><br>
<button type="submit">Calculate</button>
</form>
Process the form submission with PHP (Calculate total cost & discount):
<?php
$service = isset($_POST['service']) ? $_POST['service'] : 0;
$discount = isset($_POST['discount']) ? $_POST['discount'] : 0;
$total_discount = number_format($discount * $service, 2);
$total_cost = number_format($service - $total_discount, 2);
?>
Finally, display the total cost & discount:
<p>Discount Coupon: <input id="discount" type="text" value="&dollar;<?php echo $total_discount; ?>"/></p>
<p>Grand Total: <input id="total" type="text" value="&dollar;<?php echo $total_cost; ?>"/></p>

Calculate hidden fields with jquery

I have a form that i'm trying to calculate some monetary value based on 2 dropdowns then show the total amount only the total in a textbox called GrandTotal which is read only.
Page loads and gets pricing data from DB into hidden fields.
InitialPrice = 660 (Mandatory)
EQup1Price = 550
EQup2Price = 440
2 Drop downs (EQup1, EQup2) Values 1-5.
Buy greater than 1 and get one free for EQup1 and EQup2.
The calculation is whats doing my head in.
<p>InitialPrice -: <strong>$660.00</strong></p>
<form name="Edit" method="post" action="mypageprocess">
<p><label for="EQup1">How many Branches?</label><br /><select name="EQup1" onblur="calc(this.form)" id="EQup1"/>
<option value="0">Please select</option>
<option value="1" >One</option>
<option value="2" >Two</option>
<option value="3" >Three</option>
<option value="4" >Four</option>
<option value="5" >Five</option>
</select> x <strong>$550.00</strong>
</p>
<p><label for="EQup2">How many Satellits?</label><br /><select name="EQup2" onblur="calc(this.form)" id="EQup2"/>
<option value="0">Please select</option>
<option value="1" >One</option>
<option value="2" >Two</option>
<option value="3" >Three</option>
<option value="4" >Four</option>
<option value="5" >Five</option>
</select> x <strong>$440.00 </strong>
</p>
<input type="text" onfocus="this.blur();" name="GrandTotal" size="10" readonly="readonly"/>
<input type="hidden" name="InitialPrice" value="660" />
<input type="hidden" name="EQup1Price" value="550" />
<input type="hidden" name="EQup2Price" value="440" />
</form>
<script>
function calc(theForm) {
// console.log("calc(theForm)");
var myEquip1 = document.Edit.EQup1.value;
var myEquip2 = document.Edit.EQup2.value;
Var myFixedPrice = document.Edit.InitialPrice.value;
Var myEquip1Price = document.Edit.EQup1Price.value;
Var myEquip2Price = document.Edit.EQup2Price.value;
if (myEquip1 > 1)
{
var myEquip1Total = (myEquip1*myEquip1Price) - (myEquip1Price)
}
else
{
var myEquip1Total = (myEquip1*myEquip1Price) - (myEquip1Price)
}
if (myEquip2 > 1)
{
var myEquip2Total = (myEquip2*myEquip2Price) - (myEquip2Price)
}
else
{
var myEquip2Total = (myEquip2*myEquip2Price) - (myEquip2Price)
}
theForm.GrandTotal.value = (myEquip2Total + myEquip1Total + myFixedPrice)
}
</script>
to calculate hidden fields in jquery
$(":hidden").length
$("#GrandTotal").val(Number($("#EQup1").val()) + Number($("#EQup1").val()));

Categories

Resources