How can I detect my submit button is clicked on with javascript - javascript

Hi everyone So basically I have to code a website that calculates a certain amount using javascript, here is the exemple of the website :
Check here. So basically the client fills the form with the quantity and I have to display the total of his command, he doesn't need to submit the form
The uncomplete code is this one :
<h1>Vente de Pizza</h1>
<form method="post" action="#">
Nom du client<input type="text" name="nom" /> <br> <BR></BR>
adresse<input type="text" name="adresse" /><br>
<h1>Produits à acheter</h1>
<table border = "1">
<tr><th>Nom du produit</th>
<th>Prix unitaire</th>
<th>Quantité</th>
</tr>
<tr>
<td>Pizza 4 fromages</td>
<td>80</td>
<td><input type="text" name="QTE1" id = "x1" /></td>
</tr>
<tr>
<td>Pizza Herbo</td>
<td>75</td>
<td><input type="text" name="QTE2" id = "x2"/></td>
</tr>
<tr>
<td>Pizza viande hachée</td>
<td>100</td>
<td><input type="text" name="QTE3" id = "x3"/></td>
</tr>
<tr>
<td>Pizza Fruit de mer</td>
<td>120</td>
<td><input type="text" name="QTE4" id = "x4"/></td>
</tr>
</table>
<p font = "bold" style="font-weight: BOLD;"> Paiment par: </p><br>
<input type="radio" name="banque" id="">Carte bancaire
<input type="radio" name="banque" id="">Chèque <BR></BR>
Numéro de la carte bancaire<input type="text" name="numCB" id = "x5" style="width: 400px;"/> <br><BR>
<button class="btn" type="submit" onkeydown = "mySubmit()" id ="bouton">Envoyer</button> <BR></BR>
<script>
function TotalCalculate(){
var x1 = document.getElementById("x1").value;
var x2 = document.getElementById("x2").value;
var x3 = document.getElementById("x3").value;
var x4 = document.getElementById("x4").value;
var tot = x1*80;
document.getElementById("Total").addEventListener("click", writeTotal);
function writeTotal(){
document.getElementById("Total").write(tot);
}
}
</script>
Merci de votre visite le montant total de votre commande est :
<input type="text" name="Total" onclick="TotalCalculate()" id = "Total"/>
</form>
So as you can see I get the value from the user and calculates the total to pay, but it doesn't show anything. laybe i need to add a listner but i can't find how to add a listner that writes something.
Please help

The event you want is change or input. For example
document.querySelectorAll("input, select, textarea").forEach(function(input) {
input.addEventListener('input', TotalCalculate)
})
function TotalCalculate() {
var x1 = document.getElementById("x1").value;
var x2 = document.getElementById("x2").value;
var x3 = document.getElementById("x3").value;
var x4 = document.getElementById("x4").value;
var tot1 = x1 * 80;
var tot2 = x2 * 75; // <-- fixed these
var tot3 = x3 * 100; // <-- fixed these
var tot4 = x4 * 120; // <-- fixed these
var tot = tot1 + tot2 + tot3 + tot4;
// document.write("tot");
document.getElementById("Total").value = tot;
}
<form method="post" action="#" onsubmit="TotalCalculate(); return false">
<input type="text" id="x1"><br>
<input type="text" id="x2"><br>
<input type="text" id="x3"><br>
<input type="text" id="x4"><br>
<input type="submit">
</form>
<br>
total: <input id="Total">

Coucou,
You can use this if you have jQuery loaded
$('#bouton').on('click', function(e){
e.preventDefault();
alert('clicked');
});
or this if its only pure JS :
var button = document.getElementById('button')
button.onclick = function () {
console.log('Click just happened')
}

Related

Writing a code in javascript with radio buttons and using if else loop to calculate simple and/or compound interest

I have been asked to write a code in javascript to show the results in the output boxes based on the input data, the form should like the one shown in the attached image:Interest Calculator
Till now, I have written down the following code; however I am unable to get the results in the output boxes. Could someone please help. Thanks in advance.
function calc() {
{
var p = document.getElementById("p").value;
var r = document.getElementById("r").value;
var t = document.getElementById("t").value;
var int = f.int.value;
}
if (int === "si") {
var sip = (p * r * t) / 100
var ta = p + sip
document.getElementById("i").innerHTML = sip;
document.getElementById("a").innerHTML = ta;
} else {
var cta = p * (Math.pow((1 + r / 100), t))
var cmp = cta - p
document.getElementById("i").innerHTML = cmp;
document.getElementById("a").innerHTML = cta;
}
}
<form name="f">
<h1> Interest Calculator </h1>
Principal = <input type="text" id="p" autofocus>
<br><br><br> Rate of Interest = <input type="text" id="r">
<br><br><br> Time (in years) = <input type="text" id="t">
<br><br>
<h1> Interest Type </h1>
<input type="radio" name="int" id="int" value="si"> Simple Interest
<input type="radio" name="int" id="int" value="ci"> Compound Interest
<br><br>
<hr noshade> Interest <input type="text" id="i">
<br><br> Amount <input type="text" id="a">
<br><br>
<input type="button" name="cal" value="Calculate" onclick="calc()">
<input type="reset" value="Reset">
</form>
innerHTML is used to retrieve or update the content/markup inside a DOM node that can have children. For input elements, you have to use value to get or set the value of the field.
function calc() {
{
var p = document.getElementById("p").value;
var r = document.getElementById("r").value;
var t = document.getElementById("t").value;
var int = f.int.value;
}
if (int === "si") {
console.log("simple interest");
var sip = (p * r * t) / 100
var ta = p + sip
document.getElementById("i").value = sip;
document.getElementById("a").value = ta;
} else {
console.log("compound interest");
var cta = p * (Math.pow((1 + r / 100), t))
var cmp = cta - p
document.getElementById("i").value = cmp;
document.getElementById("a").value = cta;
}
}
<form name="f">
<h1> Interest Calculator </h1>
Principal = <input type="text" id="p" autofocus>
<br><br><br> Rate of Interest = <input type="text" id="r">
<br><br><br> Time (in years) = <input type="text" id="t">
<br><br>
<h1> Interest Type </h1>
<input type="radio" name="int" id="int" value="si"> Simple Interest
<input type="radio" name="int" id="int" value="ci"> Compound Interest
<br><br>
<hr noshade> Interest <input type="text" id="i">
<br><br> Amount <input type="text" id="a">
<br><br>
<input type="button" name="cal" value="Calculate" onclick="calc()">
<input type="reset" value="Reset"><br><br><br>
</form>
Replace innerHTML with value. Because input values are updated using value attribute. Also
the braces here
{
var p = document.getElementById("p").value;
var r = document.getElementById("r").value;
var t = document.getElementById("t").value;
var int = f.int.value;
}
is not required.
function calc() {
var p = document.getElementById("p").value;
var r = document.getElementById("r").value;
var t = document.getElementById("t").value;
var int = f.int.value;
if (int === "si") {
var sip = (p * r * t) / 100
var ta = p + sip
document.getElementById("i").value = sip;
document.getElementById("a").value = ta;
} else {
var cta = p * (Math.pow((1 + r / 100), t))
var cmp = cta - p
document.getElementById("i").value = cmp;
document.getElementById("a").value = cta;
}
}
<form name="f">
<h1> Interest Calculator </h1>
Principal = <input type="text" id="p" autofocus>
<br><br><br> Rate of Interest = <input type="text" id="r">
<br><br><br> Time (in years) = <input type="text" id="t">
<br><br>
<h1> Interest Type </h1>
<input type="radio" name="int" id="int" value="si"> Simple Interest
<input type="radio" name="int" id="int" value="ci"> Compound Interest
<br><br>
<hr noshade> Interest <input type="text" id="i">
<br><br> Amount <input type="text" id="a">
<br><br>
<input type="button" name="cal" value="Calculate" onclick="calc()">
<input type="reset" value="Reset">
</form>

unable to get check boxes value from table

I am not able to get the checkboxes values from checkboxes to Firebase.
How will I be able to get each value from each box from each row?
Table:
Check boxes:
$("#table_body_Test").append("<tr><td>" + AgentEmail + "</td><td><INPUT TYPE=\"Checkbox\" Name=\"Browser\" Value =\"Agent\"></Input></td></tr>");
Table
<div class="AgentDetailsRequest">
<table id="testTable" align="center">
<thead>
<tr style="color: #D2002E; background: #FFCC01; height:32px;">
<td>Agents</td>
<td>Select</td>
</tr>
</thead>
<tbody id="table_body_Test">
</tbody>
</table>
</div>
full form
<div class="form-popup" id="myFormDetails">
<div class="shipDetailsRequest">
<form action="" method="post" class="form-container" >
<button type="button" onclick="closeForm()" id="close">x</button>
<input name="RR" type="RRField" id="date" disabled>
<input name="RR" type="RRField" id="RRField" placeholder="RR Field" disabled>
<p>Customer Details</p>
<input onclick="sampleFunction()" type="number1" placeholder="Customer Account Number" name="customerAccountField" id="customerAccountField" required>
<input type="number1" placeholder="Customer Name" name="customerNameField" id="customerNameField" disabled>
<p>Shipper Details</p>
<input type="number1" placeholder="Shipper Name" name="senderName" id="shipperName" required>
<textarea name="collectionAddress" placeholder="Collection Address...?" id="collectionAddress"></textarea>
<p>Shipment Details</p>
<input type="text" placeholder="Enter Origin" name="shptOrigin" id="shipmentOrigin" maxlength = "3" required>
<input type="text" placeholder="Enter Destination" name="shptDest" id="shipmentDest" maxlength = "3" required>
<input type="number" placeholder="Enter Weight" name="shptWeight" id="shptWeight" required>
<input type="number" placeholder="Enter Pieces" name="shptPieces" id="shptPieces" required>
<input type="number1" placeholder="Enter Dimensions" name="shptDimensions" id="shipmentDimensions" >
<select placeholder="Choose Type" name="shptStack" id="shptStack" required>
<option value="Stackable">Stackable</option>
<option value="Nonstackable">Nonstackable</option>
</select>
<select placeholder="Choose Desk" name="Desk" id="ChooseDesk" required>
<option value="KSA">KSA Desk</option>
<option value="DHA">DHA Desk</option>
<option value="RUH">RUH Desk</option>
<option value="JED">JED Desk</option>
</select>
<p>Comment</p>
<textarea name="comment" placeholder="Other Details...?" id="commentField"></textarea>
<div class="mainDiv" align="center" >
<input type="file" id="fileButton" />
<progress id="uploader" value="0" max="100" style="max-width: 128px;">0%</progress>
</div>
<!-- <button id="submitBtn" onclick="ActionData()">Next</button> -->
<button id="submitBtn" onclick="ActionData()">Next</button>
</form>
</div>
<div class="AgentDetailsRequest">
<table id="testTable" align="center">
<thead>
<tr style="color: #D2002E; background: #FFCC01; height:32px;">
<td>Agents</td>
<td>Select</td>
</tr>
</thead>
<tbody id="table_body_Test">
</tbody>
</table>
</div>
Full JavaScript
var DateText = document.getElementById("date");
var RRText = document.getElementById("RRField");
var CustAccText = document.getElementById("customerAccountField");
var CustNameText = document.getElementById("customerNameField");
var ShipperNameText = document.getElementById("shipperName");
var CollectionAddressText = document.getElementById("collectionAddress");
var ShipmentOrgText = document.getElementById("shipmentOrigin");
var ShipmentDestText = document.getElementById("shipmentDest");
var ShipmentweightText = document.getElementById("shptWeight");
var ShipmentPiecesText = document.getElementById("shptPieces");
var ShipmentDimensionsText = document.getElementById("shipmentDimensions");
var ShptStackText = document.getElementById("shptStack");
var ChooseDeskText = document.getElementById("ChooseDesk");
var CommentText = document.getElementById("commentField");
var ShipmentOriginValues = ShipmentOrgText.value;
ShipmentOriginValues = "All";
var uploader = document.getElementById('uploader');
var fileButton = document.getElementById('fileButton');
if (ShipmentOrgText.value != null)
{
var rootRefReAgents = firebase.database().ref().child("AgentsContact").child(ShipmentOriginValues);
rootRefReAgents.on("child_added", snap =>{
var AgentEmail = snap.child("Name").val();
$("#table_body_Test").append("<tr><td>" + AgentEmail + "</td><td><INPUT TYPE=\"Checkbox\" Name=\"Browser\" Value =\"Agent\"></Input></td></tr>");
});
}
function ActionData()
{
//setting up values from Text Fields
var DateValue = DateText.value;
var RRValue = RRText.value;
var CustAccountValue = CustAccText.value;
var CustNameValue = CustNameText.value;
var ShipperNameValue = ShipperNameText.value;
var CollectionAddressValues = CollectionAddressText.value;
ShipmentOriginValues = ShipmentOrgText.value;
var ShipmentDestValues = ShipmentDestText.value;
var ShipmentweightValues = ShipmentweightText.value;
var ShipmentPiecesValues = ShipmentPiecesText.value;
var ShipmentDimensionsValues = ShipmentDimensionsText.value;
var ShptStackValues = ShptStackText.value;
var ChooseDeskValues = ChooseDeskText.value;
var CommentValues = CommentText.value;
var FirebaseRef = firebase.database().ref("Requests").child(RRValue);
if(RRValue && ShipmentOriginValues && ShipmentDestValues && CustAccountValue == null)
{
window.alert("Need More details to upload")
}
else
{
FirebaseRef.child("Date").set(DateValue);
FirebaseRef.child("RR").set(RRValue);
FirebaseRef.child("Customer Account").set(CustAccountValue);
FirebaseRef.child("Customer Name").set(CustNameValue);
FirebaseRef.child("Shipper Name").set(ShipperNameValue);
FirebaseRef.child("Collection Address").set(CollectionAddressValues);
FirebaseRef.child("Origin").set(ShipmentOriginValues);
FirebaseRef.child("Destination").set(ShipmentDestValues);
FirebaseRef.child("Weight").set(ShipmentweightValues);
FirebaseRef.child("Pieces").set(ShipmentPiecesValues);
FirebaseRef.child("Dimensions").set(ShipmentDimensionsValues);
FirebaseRef.child("Stack").set(ShptStackValues);
FirebaseRef.child("Desk").set(ChooseDeskValues);
FirebaseRef.child("Comment").set(CommentValues);
FirebaseRef.child("Status").set("Pending");
//Uploading
fileButton.addEventListener('change', function(e){
var file = e.target.files[0];
var storageRef = firebase.storage().ref('img/'+RRValue+'/'+file.name);
var task = storageRef.put(file);
task.on('state_changed', function progress(snapshot) {
var percentage = (snapshot.bytesTransferred/snapshot.totalBytes)*100;
uploader.value = percentage;
}, function error(err) {
},function complete() {
});
});
}
}
I need to check boxes from the table and get their values back to Firebase when form is submitted.
You could specify an id or name for each input and then retrieve their value when you submit the form.
$("#table_body_Test").append("<tr><td>" + AgentEmail + "</td><td><input type=\"checkbox\" id=\""+AgentEmail+"\" Value =\"Agent\"></Input></td></tr>")
var agents = ... //Get your agents list from firebase
$form.on('submit', function(){
agents.forEach(function(agent){
if($('#'+agent.email).prop('checked'){
//do something
}
})
})
If your code is working, you can ckeck if a checkbox is checked with:
/* jQuery */
if ($('#check_id').is(":checked"))
{
// checkbox is checked
}
you can also use:
/* jQuery */
$("#idOfCurrentRow").children()."input[type='checkbox']") is(":checked")
If you prefer pure JavaScript:
/* pure JavaScript*/
if(document.getElementById("idOfYourCheckbox").checked) {
...
}
or
if (document.getElementByName("nameOfYourCheckbox").checked) {
.....
}

cost splitter javascript app

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/

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>

retrieving multiple cookie values in a single cookie in javascript

I had post this problem before, dealing with the shopping cart application. The application so far does everything that i would like it to do. I'm able to store and retrieve the cookies. But right now, my problem is extracting the individual values from the cookies and placing them into a table i have created. This is the format of the cookie when retrieved.
ItemName = quantity$price. what i am trying to do is retrieve the quantity and price values from the cookie, and display that data into my table. the cookie is being created in my store page, and then retrieved and displayed in my cart page. here is the code for my store page
store.html
<html>
<head>
<title> Store </title>
<h1> My store </h1>
<script type="text/javascript">
function retr(circle)
{
var cke = document.cookie.split(';');
var nameCk= name + "=";
for(var i=0; i < cke.length; i++)
{
var c = cke [i];
while (c.charAt(0)==' ') c = c.substring(1, c.length);
if (c.indexOf(nameCk) == 0)
return c.substring(nameCk.length, c.length);
}
return null;
}
function createCookie()
{
var exdate = new Date();
exdate.setDate(exdate.getDate() +10);
if (document.getElementById("circle").checked)
{
document.cookie = "Circle=" + document.getElementById("quantity1").value + document.getElementById("price1").value + ";expires="+exdate.toGMTString();
}
}
function retrieve()
{
if (document.getElementById("circle").checked)
{
document.getElementById("ret").value = document.cookie;
}
}
function Calc()
{
var fpri = document.getElementById("price1").value;
var pri = fpri.substr(1);
var qty = document.getElementById("quantity1").value;
var spri = document.getElementById("price2").value;
var pri2 = spri.substr(1);
var qty2 = document.getElementById("quantity2").value;
if (document.getElementById("circle").checked)
{
document.getElementById("total").value ='$' + Number(pri) *
Number(qty);
}
else
document.getElementById("total").value = '$' + Number(pri2) *
Number(qty2);
}
</script>
</head>
<body>
<table border = "1">
<tr>
<td> <input type="checkbox" id="circle" /> Circle </td>
<td> <img src="circle.jpg"> </img> </td>
<td> Price: <input type="text" size="4" value = "$10.00"
id="price1" name = "price1" /></td>
<td> Quantity: <input type="text" size = "4"
id="quantity1"/></td>
</tr>
<tr>
<td> <input type = "checkbox" id="stickman" /> Stickman </td>
<td> <img src = "stickman.gif"> </img> </td>
<td> Price: <input type="text" size="4" value = "$5.00"
id="price2" /> </td>
<td> Quantity: <input type="text" size="4" id="quantity2" />
</td>
</tr>
</table>
<br />
<input type = "button" value = "Add to cart"
onclick="createCookie()">
<br />
<br />
<a href ="cart.html" > View Cart </a>
<br />
<input type = "text" size = "8" id = "total" readonly = "readonly"
/> Total
<br />
<input type = "button" id = "calcu" value = "calc" onclick = "Calc
()" />
<input type = "button" value = "retrieve" onclick = "retrieve()" />
<input type = "text" readonly = "readonly" name = "ret" id =
"ret"/>
</body>
</html>
the calculate and retrieve buttons, and the readonly text boxes are there just so i know the cookie is being stored and retrieved, and that i'm able to get the total, which will be displayed on my cart page.
here is the code for my cart page
cart.html
<html>
<head>
<title> Cart </title>
<h1> My cart </h1>
<script type = "text/javascript">
function retr(circle)
{
document.getElementById("q2").value = document.getElementById("quantity1").value
}
function retrieve()
{
var quvalue = retr("circle")
if (quvalue != false) {
document.getElementById("q2").value = quvalue
}
document.getElementById("ret").value = document.cookie;
}
</script>
</head>
<body onload = "retrieve()">
<table border = "1">
<td>Stickman </td>
<td><input type = "text" size = "8" id = "q2" readonly = "readonly" /></td>
<td id ="p1"> price per </td>
<td id ="t1"> total </td>
<tr> </tr>
<td> Circle </td>
<td> quantity order </td>
<td> price per </td>
<td> total </td>
<tr> </tr>
<td colspan = "3"> TOTAL: </td>
<td> total price </td>
</table>
<br /> <br />
<input type ="text" id = "ret" readonly = "readonly" />
<br / > <br />
<input type = "button" value = "Checkout">
<br /> <br />
<a href = "store.html" > Continue Shopping </a>
</body>
</html>
the values that are supposed to be retrieved in the table are invoked using the onload event attribute which is suppose to call the retrieve() function.
also, i understand that the way i created the table in my carts page isn't completely correct. but my main focus right now is to get the necessary values to be displayed in my table, then i will go back in rewrite my table code.

Categories

Resources