2 Identical javascripts don't run with jquery accordian - javascript

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>

Related

How can I detect my submit button is clicked on with 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')
}

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/

javascript calcultate function

i am new for javascript, im trying to calculate function but not working
<script>
function calculator() {
var first_name = document.getElementById('value1').value;
//alert("first_name");
var last_name = document.gerElementById('value2').value;
var add = first_name + last_name;
document.write("add");
}
</script>
<div id="cal">
<table>
<tr>
<td><input type="text" name="value1" id="value1" value=""></td>
<td><input type="text" name="value2" id="value2"></td>
<td><button onclick="calculator()" type="button">+</button></td>
</tr>
</table>
</div>
Tested code working fine.
<html>
<head>
<title></title>
<script type="text/javascript">
function calculator() {
var first_name = document.getElementById('value1').value;
//alert("first_name");
alert(first_name);
// var last_name = document.gerElementById('value2').value;
var last_name = document.getElementById('value2').value;
//var add = first_name+last_name;
var add = parseInt(first_name) + parseInt(last_name);
//document.write("add");
document.write(add);
}
</script>
</head>
<body>
<input id="value1" />
<input id="value2" />
<input type="button" onclick="calculator()" value="Add" />
</body>
</html>
Commented line show your code.
function calculator()
{
var first_name = parseInt(document.getElementById('value1').value);
//alert("first_name");
var last_name = parseInt(document.getElementById('value2').value);
var add = first_name + last_name;
document.write(add);
}
</script>
<table>
<tr>
<td><input type="text" name="value1" id="value1" value=""></td>
<td><input type="text" name="value2" id="value2"></td>
<td><button onclick="calculator()" type="button">+</button></td>
</tr>
</table>
</div>
You need to parseInt to perform the addition
else it will take the values as string and concatenate them
You have typo here gerElementById it should be getElementById
var last_name = document.gerElementById('value2').value;
change it to
var last_name = document.getElementById('value2').value;
and of course you are writing a string not the variable add in the document.write();
change it with
document.write(add);
check this link as well http://jsfiddle.net/E9RVn/
You are writing a string with the "add"
Remove the " " quotations
document.write(add);
They actually strings are not numbers. So, easiest way to produce a number from a string is to prepend it with +. Like :
var add = +first_name + +last_name;
<script>
function calculator() {
var first_name = document.getElementById('value1').value;
//alert("first_name");
var last_name = document.gerElementById('value2').value;
var add = parseInt(first_name) + parseInt(last_name);
document.write(add);
}
</script>
<div id="cal">
<table>
<tr>
<td><input type="text" name="value1" id="value1" value=""></td>
<td><input type="text" name="value2" id="value2"></td>
<td><button onclick="calculator()" type="button">+</button></td>
</tr>
</table>
</div>
Silly mistakes in code.
getElementById was incorrect
Values were not parsed
Below is corrected:
<script>
function calculator() {
var first_name = parseInt(document.getElementById('value1').value, 10);
//alert("first_name");
var last_name = parseInt(document.getElementById('value2').value, 10);
var add = first_name + last_name;
document.write(add);
}
</script>
<div id="cal">
<table>
<tr>
<td><input type="text" name="value1" id="value1"></td>
<td><input type="text" name="value2" id="value2"></td>
<td><button onclick="calculator()" type="button">+</button></td>
</tr>
</table>
</div>
Another way to do calculation without parsing:
<script>
function calculator() {
var first_name = document.getElementById('value1').value;
var last_name = document.getElementById('value2').value;
var cal = first_name+"+"+last_name;
var add = eval(cal);
document.write(add);
}
</script>
Ref: http://www.w3schools.com/jsref/jsref_eval.asp

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