/    Sign up×
Community /Pin to ProfileBookmark

Insert entries and perform calculations.

Hello everyone,

I’m an absolute beginner in the Javascript world, and I’m trying to get the hang of it with very few resources. As I have little idea on how to solve this obstacle of mine, I don’t know how to look for it, so I’m making a new thread.

This is the scenario, let’s see how can I explain it…
Please take a look to this example code:

[CODE]<script type=”text/javascript”>

function GetPF() {

var G_AMT = document.getElementById(“Amount”).value;
var G_TYP = document.getElementById(“Groceries”).value;

switch(G_TYP) {
case “0”:
PRICE = eval(G_AMT) * 0.5;
break;
case “1”:
PRICE = eval(G_AMT) * 0.75;
break;
case “2”:
PRICE = eval(G_AMT) * 1.5;
break;
case “3”:
PRICE = eval(G_AMT) * 1.25;
break;
}
document.getElementById(“PRICE”).innerHTML = PRICE + “$”;

}

</script>
<form name=”Grocery_List”>
<table>
<tr><th>To Buy</th><th>Amount</th><th>Price</th></tr>
<tr><td><select name=”Groceries” id=”Groceries”>
<option value=”0″>Potatoes</option>
<option value=”1″>Carrots</option>
<option value=”2″>Eggplants</option>
<option value=”3″>Zucchini</option>
</select> </td>
<td><input type=”text” name=”Amount” id=”Amount” size =”2″ /></td><td id=”PRICE”></td></tr></table>
<input type=”button” onClick=”GetPF()” value=”How much is shopping today?” />
</form>[/CODE]

So, I have a [I]not-so-handy-to-carry-around-in-the-supermarket[/I] grocery list. There is a limited data from which the user can choose from, of which the price value is stored. So, for today we’ll be only able to buy Potatoes, Carrots, Eggplants and Zucchini. In the example, however, we can only calculate the price for one kind of grocery at time: what if we actually wanted to make a list, specify the amount for each type we intend to buy, display the price for each row and, in the bottom, the grand total for our shopping?
Of course we could just add as many rows as possible entries in the list and we are done; in this case, with only four possible entries, it isn’t a hassle to do that, but what if we’re going to widen our possible list to many other types of groceries? Besides, I don’t know about you, but personally I don’t go around writing things such as “Potatoes x 0” on my grocery list, if I’m not going to buy any potatoes.

Basically, what I want to do is to make it possible (with little “+/-” buttons or something like that) for the user to add an entry in the table: that is another row with the same dropdown menu. Even if I knew how to do that (and I don’t, but I suppose I could try to use some [FONT=”Courier New”]document.write[/FONT] function?), there would be still some problem: how can I make the script not confuse the two entries and thus handling them separately (I was thinking something on the line of making progressive IDs to each addition, maybe?)? But then, how can I make the script be aware of all the instances to calculate the grand total?
Lastly — but this is entirely unneeded for my scope, I’m just asking so I can understand a little bit more of JS — what if I want to disable the options already selected somewhere else in the dropdown menu?

I thank you very much in advance. An answer to any of these questions is greatly appreciated.
Now I must go shopping without knowing how much will I spend! ?

Best regards,

M. L.

to post a comment
JavaScript

2 Comments(s)

Copy linkTweet thisAlerts:
@justinbarneskinOct 23.2008 — ? That's too bad that you need to clip coupons and count your money.

When you get rid of your wagon and only buy what you can walk with, life becomes easier and, maybe coding aspirations become more practical.

[SIZE="1"]

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<HTML>

<HEAD><TITLE>GroceryList</TITLE>

<META http-equiv=Content-Type content="text/html; charset=UTF-8">

<STYLE type=text/CSS>

body{color:112233;}

A:link{font-family:comic sans ms;text-decoration:none;color:#0033ff}

A:visited{font-family:comic sans ms;text-decoration:none;color:#0099ff;font-size:14px}



.checkbox{width:20px;height:20px;}

.item{width:119px;border:0px inset silver;margin:1px;overflow:hidden}

#list{font-family:segoe print,comic sans ms,monotype corsiva;font-size:20px;width:280px;border:1px dashed silver;text-align:center;text-decoration:none}

#ml{width:45px;background:#550055;color:white;font-size:12px}

</STYLE>



<SCRIPT type="text/javascript">





//setCookie(isName,isValue,daysExpire) dispCookie(isName) deleteCookie(isName)





var expDate = new Date();

function setCookie(isName,isValue,daysExpire){
expDate = new Date();
if(daysExpire){ expDate.setTime(expDate.getTime()+(86400000*daysExpire)); }
else{expDate.setTime(expDate.getTime()+24*60*60*1000*365);}
document.cookie = isName+"="+escape(isValue)+";expires="+expDate.toGMTString();
}

function getCookie(isName){
var cookieStr = document.cookie;
var startSlice = cookieStr.indexOf(isName+"=");

if (startSlice == -1){return false}
var endSlice = cookieStr.indexOf(";",startSlice+1);
if (endSlice == -1){endSlice = cookieStr.length}
var isData = cookieStr.substring(startSlice,endSlice);
var isValue = isData.substring(isData.indexOf("=")+1,isData.length);
return unescape(isValue);
}

function dispCookie(isName){
var nValue = getCookie(isName);
return (nValue);
}

function deleteCookie(isName){
if (getCookie(isName)){document.cookie = isName + "="+
"; expires=Thu, 01-Jan-02 00:00:01 GMT";}
}


var food=new Array('DeliChicken','DeliSandwich','Cheese','PotatoSalad','LunchMeat','HDogs','Burritos','Butter','H-buns','CinRolls','eggs','Bread','Jelly/Honey','PeanButter','Milk','Chips','Choc/Candy','OatMeal','PancakeMix','Syrup','Tea','Coffee','Cereal','Cookies','Cashews','IceCream','Pizza','Dinners','ChickenPatties','Hamburger','FrznSpuds','Sausage','V8/OJ','CannedVegs','Chili','Beans','SaladDressing','Salmon/tuna','Ketch/Mustard','Apples','Tomato','Onion','Raisins','Apricots','Potatoes','Pickles','LighBulbs','Dish/laundry','Soap','Shampoo','TthPst/Brsh','Deodrant','Blades','TP','Comet*','Lemon','Sugar/Salt','Pam')

function listIt(display){

var y=''; var r=5;

y+='<DIV style="position:absolute;z-index:2;background:black;width:485px;left:2px;top:2px">';

for (i=0; i<food.length; i++ ) {

y+='<span class="item"><input type=checkbox value="'+food[i]+'" class="checkbox" onclick="upDateList();window.focus()"><a href="javascript:void(0)" onclick="document.getElementsByTagName('span')['+i+'].style.display='none'">'+food[i]+'</a></span>'; }

y+='<input id="extraItem" size=10 onchange="setCookie('extra',this.value)">';

y+='<br><span class=item><input type=button onclick="MakeListToPrint()" value="Make List"></span><span class=item><span class="item"><input type=button onclick="showMoreLess(''+display+'')" value="&#9650; &nbsp; &#9660;" id="ml"></span></DIV>';



document.forms[0].innerHTML=y;
if(dispCookie("extra")){document.getElementById('extraItem').value=dispCookie("extra"); }

setTimeout("checkList('"+display+"')",30);

}

function upDateList(display){ var gList=new Array();

k=document.forms[0].elements;

for(i=0;i<food.length;i++){if(k[i].checked){gList[gList.length]=1} else{gList[gList.length]=0;t[i].style.color='blue'}}

setCookie("groceries",gList);checkList(display)

}

function checkList(display){

k=document.forms[0].elements;

t=document.links;

if(dispCookie("groceries")){

for(i=0,j=0;i<food.length;i++,j+=2){if(dispCookie("groceries").charAt(j)==1){k[i].checked=true;t[i].style.color='red'}}

}

else{for(i=0;i<food.length;i++){k[i].checked=false;}}



//---hides items

var s=document.getElementsByTagName('span')

if(display=='none'){for(i=45;i<=s.length-4;i++){s[i].style.display='none';s[i].style.background='#290029';}

}

else{for(i=45;i<=s.length-4;i++){s[i].style.background='#290029';}

}

}



function showMoreLess(x){

if(x=='none'){listIt('block')}

else if(x=='block'){listIt('none')}

}



function rc(){return ((120*Math.random())+10)}

function MakeListToPrint(){

k=document.forms[0].elements;

var j='';

for(i=0;i<k.length;i++){if(k[i].checked){j+='<span style="color:rgb('+rc()+','+rc()+','+rc()+');">'+k[i].value+',</span> '}}

if(document.getElementById('extraItem').value){j+='<span style="color:rgb('+rc()+','+rc()+','+rc()+');">'+document.getElementById('extraItem').value+',</span> '}

document.forms[0].style.display='none'

document.getElementById('list').innerHTML=j

}



</SCRIPT>

<META content="MSHTML 6.00.2900.2963" name=GENERATOR></HEAD>

<BODY scroll="auto" >

<form>



<SCRIPT type="text/javascript">

document.write(listIt('none'))



</SCRIPT>



</form>

<div ID="list"></div>











</BODY></HTML>



[/SIZE]
Copy linkTweet thisAlerts:
@belthasarauthorOct 23.2008 — Hello Justin,

Thank you very much for your concern and for the time you spent on helping me, I'm sure I can learn quite a lot from the code you posted.

Alas &#8212; I don't mean to be disrespectful &#8212; it doesn't really address my issue, which is mainly to perform calculations.

With the code you provided I cannot attach an amount to each selected object, nor I can use that amount as a base to perform calculations (and, also I cannot attach a price to each object to form the other variable I need).

Would my idea of letting the user add a table row really be so unrealistic?

Regards,

M. L.
×

Success!

Help @belthasar spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 5.20,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @AriseFacilitySolutions09,
tipped: article
amount: 1000 SATS,

tipper: @Yussuf4331,
tipped: article
amount: 1000 SATS,

tipper: @darkwebsites540,
tipped: article
amount: 10 SATS,
)...