Macchiato Posted September 8, 2011 Share Posted September 8, 2011 I´d like to get the amount between "(+$" and ")" and add it to the value of the inputbox. For example, you select the following:Solero Exotic (+$1.85)Cappuccino (+$2.49)iMac 27-inch 3.1GHz (+$1,999.00) These amounts will be subtracted from the options you've selected:1.852.491,999.00 The inputbox will display: 2003.34 But here's the tricky part, I need to do this without changing the existing attribute values or adding new attributes to the Option tag. Anyone know a javascript code that can do this? If possible, please post a sample. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Get Amount And Put Elsewhere</title></head> <body> <form action=""> <fieldset> <ul style="list-style:none;padding-left:0;"> <li>Ice Cream: <select class="optionsIceCream" name="IceCream"> <option value="IceCream01">Select Ice Cream</option> <option value="IceCream02">Solero Exotic (+$1.85)</option> <option value="IceCream03">Magnum Ecuador (+$4.85)</option> <option value="IceCream04">Cornetto Enigma (+$2.00)</option> </select> </li> <li>Coffee: <select class="optionsCoffee" name="Coffee"> <option value="Coffee01">Select Coffee</option> <option value="Coffee02">Cup of Joe (+$0.99)</option> <option value="Coffee03">Cappuccino (+$2.49)</option> <option value="Coffee04">Latte Macchiato (+$2.99)</option> </select> </li> <li>Computers: <select class="optionsComputers" name="Computers"> <option value="Computer01">Select Computer</option> <option value="Computer02">Dell Inspiron 620 (+$449.99)</option> <option value="Computer03">HP Pavilion dv7t (+$949.99)</option> <option value="Computer04">iMac 27-inch 3.1GHz (+$1,999.00)</option> </select> </li> </ul> Total: <input class="totalAmount" type="text" disabled="disabled" value="0.00" /> </fieldset> </form> </body></html> Link to comment Share on other sites More sharing options...
ShadowMage Posted September 8, 2011 Share Posted September 8, 2011 You might want to check out regular expressions. Link to comment Share on other sites More sharing options...
thescientist Posted September 8, 2011 Share Posted September 8, 2011 assuming the convention is the same, in that there will always be a (+$ + some decimal + ), worst case scenario you could always use some of JS's string methods to extract what comes after the $ and before the first ). (or just the length of the string -1). Link to comment Share on other sites More sharing options...
ShadowMage Posted September 8, 2011 Share Posted September 8, 2011 You'll have to remove all the commas, too. If you keep the convention the same, scientist's suggestion would be far simpler. Link to comment Share on other sites More sharing options...
Drycodez Posted September 9, 2011 Share Posted September 9, 2011 RegExp=/\d+,?\d*\.\d+(?=\))/rexExp like that can help! Link to comment Share on other sites More sharing options...
Macchiato Posted September 9, 2011 Author Share Posted September 9, 2011 I found a solution, thanks to Dominic H from Yahoo! Answers It's simple but very effective and it works perfectly! Here's the entire code: <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Get Amount And Put Elsewhere</title></head> <body> <form action=""> <fieldset> <ul style="list-style:none;padding-left:0;"> <li>Ice Cream: <select class="optionsIceCream" name="IceCream"> <option value="IceCream01">Select Ice Cream</option> <option value="IceCream02">Solero Exotic (+$1.85)</option> <option value="IceCream03">Magnum Ecuador (+$4.85)</option> <option value="IceCream04">Cornetto Enigma (+$2.00)</option> </select> </li> <li>Coffee: <select class="optionsCoffee" name="Coffee"> <option value="Coffee01">Select Coffee</option> <option value="Coffee02">Cup of Joe (+$0.99)</option> <option value="Coffee03">Cappuccino (+$2.49)</option> <option value="Coffee04">Latte Macchiato (+$2.99)</option> </select> </li> <li>Computers: <select class="optionsComputers" name="Computers"> <option value="Computer01">Select Computer</option> <option value="Computer02">Dell Inspiron 620 (+$449.99)</option> <option value="Computer03">HP Pavilion dv7t (+$949.99)</option> <option value="Computer04">iMac 27-inch 3.1GHz (+$1,999.00)</option> </select> </li> </ul> Total: <input class="totalAmount" type="text" disabled="disabled" value="0.00" /> </fieldset> </form> <script type="text/javascript"> //<![CDATA[ (function () { var selects = document.getElementsByTagName("select"), L = selects.length, i; for (i = 0; i < L; i++) { selects[i].setAttribute("onchange", "calcTotal();"); } }()); function calcTotal() { var icecream = [0.00, 1.85, 4.85, 2.00], coffee = [0.00, 0.99, 2.49, 2.99], computer = [0.00, 449.99, 949.99, 1999.00], total = document.getElementsByTagName("input")[0], select = document.getElementsByTagName("select"); total.value = (icecream[select[0].selectedIndex] + coffee[select[1].selectedIndex] + computer[select[2].selectedIndex]).toFixed(2); } //]]></script> </body></html> Link to comment Share on other sites More sharing options...
ShadowMage Posted September 9, 2011 Share Posted September 9, 2011 That solution may work now, but what if you wanted to add more options? Or rearrange them? Or add another select? You'd have to rewrite a bunch of code and add things to accommodate the new items. That code isn't very scalable. You'd be better to use the technique that scientist posted and write a generic function to calculate the total. Something like: <form id='options' action=""> <fieldset> <ul style="list-style:none;padding-left:0;"> ...Select elements here... </ul> Total: <input id='total' class="totalAmount" type="text" disabled="disabled" value="0.00" /> </fieldset></form> <script type="text/javascript"> //<![CDATA[ var optsForm = document.getElementById('options'); var selects = optsForm.getElementsByTagName("select"), L = selects.length, i; for (i = 0; i < L; i++) { selects[i].onchange = calcTotal; } function calcTotal() { var totalEl = document.getElementById("total"), totalVal = 0, selects = optsForm.getElementsByTagName("select"); for (var x=0, y=selects.length; x<y; x++) { var value = selects[x].options[selects[x].selectedIndex].text; value = value.substring(value.search(/[(]\+[$]/)+3, value.length-1); value = value.replace(/,/g, ''); totalVal += Number(value); } totalEl.value = totalVal; } //]]></script> This is just off the top of my head. I haven't tested it yet so there's likely to be errors. EDIT: Tested and updated the code to a working version. Notice how I've given your form an id. This will allow you to limit the selects to only those in that form. If you have selects in another portion of the page, they won't interfere. You could limit that further by giving the id to the ul instead thereby limiting it to only the selects within that list, allowing you to have other selects within the same form.You get a reference to your selects by using the element you specify the id for when you use getElementsByTagName instead of using the document object.The guts of this thing though, is in the calcTotal function. The for loop in there loops through all the select elements (retrieved from the form using getElementsByTagName) and gets their text value. It extracts the portion of the string between '(+$' and the last character in the string, which should be ')' if you keep your convention the same. It converts that into a number and adds it to the total. Then it puts the total into your input. Link to comment Share on other sites More sharing options...
Macchiato Posted September 12, 2011 Author Share Posted September 12, 2011 Sorry for the late reply. Your code is great, especially because it can handle commas (,) in the amount. There's only one problem: if you select, for example: Solero Exotic (+$1.85)Select CoffeeHP Pavilion dv7t (+$949.99) You get "NaN" instead of $951.84 P.S. Works in ie7 and ie8, but doesn't seem to work in ie6. Link to comment Share on other sites More sharing options...
JamesB Posted September 12, 2011 Share Posted September 12, 2011 to skip the top <option>'s you can probably just add an if check, by changing var value = selects[x].options[selects[x].selectedIndex].text;value = value.substring(value.search(/[(]\+[$]/)+3, value.length-1);value = value.replace(/,/g, '');totalVal += Number(value); to var index = selects[x].selectedIndex;if (index) { var value = selects[x].options[index].text; value = value.substring(value.search(/[(]\+[$]/)+3, value.length-1); value = value.replace(/,/g, ''); totalVal += Number(value);} Link to comment Share on other sites More sharing options...
Macchiato Posted September 12, 2011 Author Share Posted September 12, 2011 Thanks JamesB, works like a charm now, and your edit also fixes the problem with ie6! Link to comment Share on other sites More sharing options...
Macchiato Posted September 12, 2011 Author Share Posted September 12, 2011 I was wondering, is there any way to put a "$" sign in the inputbox, in front of the amount, without messing up the code? Link to comment Share on other sites More sharing options...
ShadowMage Posted September 12, 2011 Share Posted September 12, 2011 I was wondering, is there any way to put a "$" sign in the inputbox, in front of the amount, without messing up the code?Sure:totalEl.value = "$"+totalVal;Be aware, though, that if you want to save this value into a database you'll have to strip the dollar sign back off before you do. That's a pretty trivial task though. Link to comment Share on other sites More sharing options...
Macchiato Posted September 12, 2011 Author Share Posted September 12, 2011 Thanks for the fast reply ShadowMage! It works perfectly Be aware, though, that if you want to save this value into a database you'll have to strip the dollar sign back off before you do. That's a pretty trivial task though. Good thing I don't have to save it in a database, for now at least Link to comment Share on other sites More sharing options...
Macchiato Posted September 14, 2011 Author Share Posted September 14, 2011 What needs to be changed to the code if I want to send the total amount to a P element instead of the value of the inputbox? Total: <p id="total">$0.00</p> instead of:Total: <input id="total" type="text" disabled="disabled" value="$0.00" /> Link to comment Share on other sites More sharing options...
Ingolme Posted September 14, 2011 Share Posted September 14, 2011 Something like this: document.getElementById('total').innerHTML = value; Link to comment Share on other sites More sharing options...
Macchiato Posted September 14, 2011 Author Share Posted September 14, 2011 You mean like this? ... Total: <p id="total">$0.00</p> <script type="text/javascript">function getAmountAndPutElsewhere(id) { var checkForThisID = document.getElementById(id); var getAmountSelects = checkForThisID.getElementsByTagName("select"), L = getAmountSelects.length, i; for (i = 0; i < L; i++) { getAmountSelects[i].onchange = calcTotal; } function calcTotal() { var totalEl = document.getElementById("total").innerHTML = value; totalVal = 0, getAmountSelects = checkForThisID.getElementsByTagName("select"); for (var x=0, y=getAmountSelects.length; x<y; x++) { var index = getAmountSelects[x].selectedIndex; if (index) { var value = getAmountSelects[x].options[index].text; value = value.substring(value.search(/[(]\+[$]/)+3, value.length-1); value = value.replace(/,/g, ''); totalVal += Number(value); } } totalEl.value = "$"+totalVal; }}getAmountAndPutElsewhere("getAmountAndPut");</script> P displays "undefined" Link to comment Share on other sites More sharing options...
dsonesuk Posted September 14, 2011 Share Posted September 14, 2011 No, where the total is assigned to totalEl.value totalEl.value = "$"+totalVal;document.getElementById('total').innerHTML = "$"+totalVal;ORtotalEl.value = "$"+totalVal;document.getElementById('total').innerHTML = "$"+totalEl.value;as totalEl.value has been assigned the value of "$"+totalVal beforehand. Link to comment Share on other sites More sharing options...
ShadowMage Posted September 14, 2011 Share Posted September 14, 2011 Actually totalEl should be a reference to the element that will recieve the total value (ie, the input in the old code, the p in the new code). So the only thing that would need to change is this line: totalEl.value = "$"+totalVal; to: totalEl.innerHTML = "$"+totalVal; Link to comment Share on other sites More sharing options...
Macchiato Posted September 14, 2011 Author Share Posted September 14, 2011 Actually totalEl should be a reference to the element that will recieve the total value (ie, the input in the old code, the p in the new code). So the only thing that would need to change is this line: totalEl.value = "$"+totalVal; to: totalEl.innerHTML = "$"+totalVal; Works like a charm, many thanks! Link to comment Share on other sites More sharing options...
Macchiato Posted September 15, 2011 Author Share Posted September 15, 2011 I replaced: totalEl.innerHTML = "$"+totalVal; with: totalEl.innerHTML = "$"+totalVal.toFixed(2); To get $1999.00 instead of $1999 I was wondering, what do you have to change to the code to get a comma (,) in the amount, so you get $1,999.00 instead of $1999.00 See an example of the code here Link to comment Share on other sites More sharing options...
dsonesuk Posted September 15, 2011 Share Posted September 15, 2011 ??? run it through function you already have function addCommasandsign(nStr) {nStr += '';x = nStr.split('.');x1 = x[0];x2 = x.length > 1 ? '.' + x[1] : '';var rgx = /(\d+)(\d{3})/;while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2');}return '$' + x1 + x2; } totalEl.innerHTML = addCommasandsign(totalVal.toFixed(2)); Link to comment Share on other sites More sharing options...
Macchiato Posted September 15, 2011 Author Share Posted September 15, 2011 ??? run it through function you already have function addCommasandsign(nStr) {nStr += '';x = nStr.split('.');x1 = x[0];x2 = x.length > 1 ? '.' + x[1] : '';var rgx = /(\d+)(\d{3})/;while (rgx.test(x1)) { x1 = x1.replace(rgx, '$1' + ',' + '$2');}return '$' + x1 + x2; } totalEl.innerHTML = addCommasandsign(totalVal.toFixed(2)); You're right, it works! I had no idea it was compatible with your code, thanks dsonesuk Updated code here Link to comment Share on other sites More sharing options...
ShadowMage Posted September 15, 2011 Share Posted September 15, 2011 AFAIK, JavaScript does not have a built-in function to add commas. I wrote a custom one myself that you could use if you like: function format(num, dec) { if (dec !== undefined) { num = num.toFixed(dec); } var numStr = num.toString(); var parts = numStr.split('.'); numStr = parts[0]; var decimals = (parts[1])?parts[1]:''; var newStr = [], counter = 0; for (var x=numStr.length-1; x>=0; x--) { if (counter >= 3) { newStr.unshift(','); counter = 0; } newStr.unshift(numStr[x]); counter++; } newStr = newStr.join(''); if (decimals != '') { newStr += '.'+decimals; } return newStr;} You would use it like this:totalEl.innerHTML = "$"+format(totalVal, 2); EDIT: Guess I was too slow! :PEDIT EDIT: I really hate the way this new forum version messes with your code snippets after an edit..... Link to comment Share on other sites More sharing options...
Macchiato Posted September 17, 2011 Author Share Posted September 17, 2011 Thanks ShadowMage! EDIT: Guess I was too slow! Just a wee bit Link to comment Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.