SitePoint Sponsor

User Tag List

Results 1 to 18 of 18
  1. #1
    SitePoint Enthusiast
    Join Date
    Dec 2008
    Posts
    46
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    adding two variables and display in HTML

    I'm new to javascript and i'm sure there is a better way yto do this and save the sum of the two in a variable and display the variable:

    <script type="text/javascript">
    var textBlocks = new Array(
    '$4.99',
    '$8.99');

    function changetext(elemid) {
    var ind = document.getElementById(elemid).selectedIndex;
    document.getElementById("display").innerHTML=textBlocks[ind];
    }
    </script>
    <script type="text/javascript">
    <!--
    function showMe (it, box) {
    var vis = (box.checked) ? "block" : "none";
    document.getElementById(it).style.display = vis;
    }
    //-->
    </script>


    ================================================================================


    <table width="100%" border="0" cellspacing="0" cellpadding="3">
    <tr>
    <td height="21" colspan="2" align="left" valign="middle" bgcolor="#54A0D1"><div align="left" class="style1">Description</div></td>
    <td width="25%" height="21" bgcolor="#54A0D1"><div align="center" class="style1">PRICE</div></td>
    </tr>
    <tr>
    <td colspan="2" align="left" valign="middle"><strong>TheColonDiet 14-day Risk Free Trial</strong></td>
    <td width="25%" align="center" valign="middle">FREE</td>
    </tr>
    <tr>
    <td width="13%" align="left" valign="middle"><strong>Shipping/strong></td>
    <td width="62%" align="left" valign="middle">
    <select id="shipping" onchange="changetext('shipping');">
    <option value="4.99" selected="selected">Ground ($4.99)</option>
    <option value="8.99">Expedited ($8.99)</option>
    </select> </td>
    <td align="center" valign="middle"><div id="display">$4.99</div></td>
    </tr>
    <tr>
    <td align="right" valign="middle"><input name="modtype" type="checkbox" onclick="showMe('div1', this)" value="1" checked="checked" /></td>
    <td align="left" valign="middle">Yes, Please insure my order for only $1.00</td>
    <td align="center" valign="middle"><div class="row" id="div1" style="display:vis">$1.00</div></td>
    </tr>
    <tr>
    <td colspan="2" align="left" valign="middle">&nbsp;</td>
    <td width="25%" align="center" valign="middle">&nbsp;</td>
    </tr>
    </table>

    Right now it does what i need up as far as dynamically changing the text based on teh selections. How can i save the total of the drop-down and checkbox value?

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    If you're wanting to save it to a database, you'll need to use some kind of server-side script like php, which accepts the total and accesses the database for you.
    The people in the php forum will be able to help you with that, for the purposes of using ajax to update the database.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  3. #3
    SitePoint Enthusiast
    Join Date
    Dec 2008
    Posts
    46
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I'm aware of that. I'm usinmg ASP to save to a database. I simply need to display an updated total (dynamically - with reloading the page) if and when the drop-down selection is changed or if the check box is cheked/unchecked.

  4. #4
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    So that it doesn't mean too many changes from what you're doing right now, you can update the onchange event for the select.

    Code html4strict:
    <select id="shipping" onchange="updateTextAndTotal(this.id);">

    Code javascript:
    function updateTextAndTotal(select) {
        changetext(select);
        updateTotalFromSelect(select);
    }
    function updateTotalFromSelect(select) {
        var total = document.getElementById('myTotal');
        total.value = select.options[select.selectedIndex];
    }
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  5. #5
    SitePoint Enthusiast
    Join Date
    Dec 2008
    Posts
    46
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks. I'm a little confused...
    where does (myTotal) come from? How can i display teh total as inline html?

    here's an example of what i'm trying to do:

    www.thecolondiet.com/order.php

    I know they're using php. I need to replicate the effect of teh dynamic price change using javascript and a drop-down for the shipping option.

  6. #6
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by neoArm View Post
    Thanks. I'm a little confused...
    where does (myTotal) come from?
    The myTotal identifier would be on the html element that you intend to use to display the total. I didn't see in your code a place for the total, so presumed that you would use a disabled input field to easily show it without it being able to be changed.

    Quote Originally Posted by neoArm View Post
    How can i display teh total as inline html?
    That changes things then, but not too drastically. Here is the updated updateTotalFromSelect function to do just that.

    Code javascript:
    function updateTotalFromSelect(select) {
        var total = document.getElementById('myTotal');
        total.innerHTML = select.options[select.selectedIndex];
    }

    The only change in the above code is that total.value became total.innerHTML

    If you don't wish to use the innerHTML method, here is the complete standards-based way to achieve it.

    Code javascript:
    function updateTotalFromSelect(select) {
        var total = document.getElementById('myTotal');
        var value = select.options[select.selectedIndex];
        replaceElementContents(total, value);
    }
    function replaceElementContents(el, text) {
        var text = document.createTextNode(text);
        while (el.hasChildNodes()) {
            el.removeChild(el.firstChild);
        }
        el.appendChild(text);
    }
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  7. #7
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    Oh yes, and the HTML will want a small piece of code in which to put the total. Instead of using myTotal we'll use a name that better represents its purpose. That being something like:

    Code html4strict:
    The total price is: <span id="totalPrice">&nbsp;</span>

    That together with the javascript should see you right.

    Code javascript:
    function updateTotalFromSelect(select) {
        var total = document.getElementById('totalPrice');
        total.innerHTML = select.options[select.selectedIndex];
    }
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  8. #8
    SitePoint Enthusiast
    Join Date
    Dec 2008
    Posts
    46
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    I'm completely lost. This is what I have:

    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    <script type="text/javascript"> 
    
    var textBlocks = new Array( 
    '$4.99', 
    '$8.99'); 
    
    function changetext(elemid) { 
    var ind = document.getElementById(elemid).selectedIndex; 
    document.getElementById("display").innerHTML=textBlocks[ind]; 
    } 
    </script> 
    <script type="text/javascript">
            <!--
            function showMe (it, box) {
              var vis = (box.checked) ? "block" : "none";
              document.getElementById(it).style.display = vis;
            }
            //-->
    </script>
    <style type="text/css">
    <!--
    .style1 {	color: #FFFFFF;
    	font-weight: bold;
    }
    -->
    </style>
    </head>
    
    <body>
    <table width="35&#37;" border="0" align="center" cellpadding="3" cellspacing="0">
      <tr>
        <td height="21" colspan="2" align="left" valign="middle" bgcolor="#54A0D1"><div align="left" class="style1">Description</div></td>
        <td width="25%" height="21" bgcolor="#54A0D1"><div align="center" class="style1">PRICE</div></td>
      </tr>
      <tr>
        <td colspan="2" align="left" valign="middle">&nbsp;</td>
        <td align="center" valign="middle">&nbsp;</td>
      </tr>
      <tr>
        <td colspan="2" align="left" valign="middle"><strong>Product Name</strong></td>
        <td width="25%" align="center" valign="middle"><strong>FREE</strong></td>
      </tr>
      <tr>
        <td width="13%" align="left" valign="middle"><strong>Shipping:</strong></td>
        <td width="62%" align="left" valign="middle"><select name="shipping" id="shipping" onchange="changetext('shipping');">
          <option value="4.99" selected="selected">Ground ($4.99)</option>
          <option value="8.99">Expedited ($8.99)</option>
        </select>
        </td>
        <td align="center" valign="middle"><div id="display">$4.99</div></td>
      </tr>
      <tr>
        <td align="right" valign="middle"><input name="modtype" id="modtype" type="checkbox" onclick="showMe('div1', this)"  value="1.00" checked="checked" /></td>
        <td align="left" valign="middle">Yes, Please insure my order for only $1.00</td>
        <td align="center" valign="middle"><div class="row" id="div1" style="display:vis">$1.00</div></td>
      </tr>
      <tr>
        <td colspan="2" align="left" valign="middle">&nbsp;</td>
        <td width="25%" align="center" valign="middle"><strong>TOTAL</strong></td>
      </tr>
    </table>
    </body>
    </html>
    Please run the code and advise on how i can get the total to appear where i've inserted the word TOTAL. Thanks for your patience.

  9. #9
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    Place an identifier on the area where the total is going to be.

    Code html4strict:
    <strong>TOTAL</strong> <span id="totalPrice">&nbsp;</span>

    Update the total whenever the select or the checkbox changes.

    Code javascript:
    function changetext(elemid) { 
    	var ind = document.getElementById(elemid).selectedIndex; 
    	document.getElementById("display").innerHTML=textBlocks[ind]; 
    	updateTotal();
    }
    function showMe (it, box) {
        var vis = (box.checked) ? "block" : "none";
        document.getElementById(it).style.display = vis;
        updateTotal();
    }

    When it comes time to perform the update, get the price from the select and insurance fields, add them together and use to update the totalPrice area on the page.

    Code javascript:
    function updateTotal() {
    	var shipping = document.getElementById('shipping');
    	var shippingValue = shipping.options[shipping.selectedIndex].value;
    	var shippingPrice = parseFloat(shippingValue);
    	var insurance = document.getElementById('modtype');
    	var insuranceValue = insurance.checked ? insurance.value : 0;
    	var insurancePrice = parseFloat(insuranceValue);
    	var total = document.getElementById('totalPrice');
    	total.innerHTML = (shippingPrice + insurancePrice).toFixed(2);
    }

    And finally when the page first loads, update the price then as well.

    Code javascript:
    window.onload = updateTotal;
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  10. #10
    SitePoint Enthusiast
    Join Date
    Dec 2008
    Posts
    46
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    You Rock!

  11. #11
    SitePoint Enthusiast
    Join Date
    Dec 2008
    Posts
    46
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    How can i also store the updated total in a hidden textfield?

  12. #12
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    Have a hidden field called total, and update that from the updateTotal function.

    Code javascript:
    <input type="hidden" name="total">

    Code javascript:
    function updateTotal() {
        var shipping = document.getElementById('shipping');
        var shippingValue = shipping.options[shipping.selectedIndex].value;
        var shippingPrice = parseFloat(shippingValue);
        var insurance = document.getElementById('modtype');
        var insuranceValue = insurance.checked ? insurance.value : 0;
        var insurancePrice = parseFloat(insuranceValue);
        var totalPrice = (shippingPrice + insurancePrice).toFixed(2);
        var totalElement = document.getElementById('totalPrice');
        var totalField = document.getElementsByName('total')[0];
        totalElement.innerHTML = totalPrice;
        totalField.value = totalPrice;
    }

    Edit:

    Changed getElementByName to getElementsByName
    Last edited by paul_wilkins; Dec 29, 2008 at 23:30.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  13. #13
    SitePoint Enthusiast
    Join Date
    Dec 2008
    Posts
    46
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    didn't work

  14. #14
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    And now, in the spirit of Colette from Ratatouille, here are some updates.

    First of all you shouldn't use a transitional doctype. It's entirely possible to properly validate with a strict doctype so let's step up to the plate and get on with it.

    Code html4strict:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    Next up what do we see here. It's an untitled document. Oh dear me no, please don't leave it like that. Give it a name! So that people can bookmark the page and find it again.

    Code html4strict:
    <title>The Colon Diet - Purchase</title>

    Next up we have some horrible code that needs to be completely cleansed.

    Code javascript:
    var textBlocks = new Array( 
    '$4.99', 
    '$8.99'); 
     
    function changetext(elemid) { 
    	var ind = document.getElementById(elemid).selectedIndex; 
    	document.getElementById("display").innerHTML=textBlocks[ind]; 
    	updateTotal();
    }

    It duplicates what is already on the page and is guaranteed to cause problems when the prices change later on.

    The textBlocks array isn't needed, because those values can come from the select field that's already on the page, and the changetext function I'll rename to updateFromSelect so that we can have some consistant names occurring here.

    The updateById function will be a useful one for many of our functions to call, whenever they have to update a section of the page.

    Because the updateFromSelect function is now quite specialised, we should update the totalPrice from a different place. We'll create a function to update the shipping, and call that from the select field itself, and take the opportunity to change the identifier from display to shippingPrice as well.

    Code javascript:
    function updateShipping(el) {
    	var value = getSelectValue(select);
    	updateById('shippingPrice', toDollar(value));
    	updateTotal();
    }
    function updateById(id, text) {
    	document.getElementById(id).innerHTML = text;
    }

    The toDollar function adds on a dollar symbol, and checks to make sure that the value makes sense. If no sensible value come in, it returns $0.00 instead.

    Code javascript:
    function toDollar(value){
    	value = parseFloat(value);
    	if (!Number(value)) {
    		value = 0;
    	}
        return '$' + value.toFixed(2);
    }

    Notice the pattern that's occuring here. The functions are being made to be quite generic, so they can be used multiple times by different parts of the code.

    We can perform a similar update to the showme function, which I'll rename to updateFromCheckbox, and use updateInsurance to call it and update the total. I'll also take this opportunity to change the identifier of div1 to insurancePrice

    Code javascript:
    function updateInsurance(checkbox) {
    	var value = getCheckedValue(checkbox);
    	updateById('insurancePrice', toDollar(value));
    	updateTotal();
    }
    function getCheckedValue(checkbox) {
    	if (checkbox.checked) {
    		return checkbox.value;
    	}
    }

    A later update for when the form grows further is that we could even have an updateField function, so that the duplicated code in updateShipping and updateInsurance can be taken care of.

    But now, we can finish up the scripting with the updateTotal function:

    Code javascript:
    function updateTotal() {
        var total = calculateTotal();
    	updateById('totalPrice', toDollar(total));
    }
    function calculateTotal() {
    	var shipping = document.getElementById('shipping');
    	var shippingValue = getSelectValue(shipping);
    	var shippingPrice = parseFloat(shippingValue) || 0;
    	var insurance = document.getElementById('modtype');
    	var insuranceValue = getCheckedValue(insurance);
    	var insurancePrice = parseFloat(insuranceValue) || 0;
    	return shippingPrice + insurancePrice;
    }
    updateTotal();

    These scripts are going to be placed at the end of the body, just before the </body> tag where they belong, which also means that onload techniques are not required. Hurrah!

    Next up, shifting the presentation from HTML to CSS
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  15. #15
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    Quote Originally Posted by neoArm View Post
    didn't work
    My apologies, there was a spelling error in there. getElementByName should have been getElementsByName - try that now.
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  16. #16
    SitePoint Enthusiast
    Join Date
    Dec 2008
    Posts
    46
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you, Paul. I got it to work by changing getElementByName to getElementsByName

    I'll explore the what you posted on the spirit of Colette from Ratatouille.

  17. #17
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    Cheers.

    I did have quite a lot to say about the css as well, but fortune has it that I lost it with the strike of a key, so here's the updated code with the separate css, html and javscript all working together, and together allowing easier updates to the page.

    Code html4strict:
    <!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>The Colon Diet - Purchase</title>
    <style type="text/css">
    #productOrder {
    	width: 35%;
    	border: none;
    	margin: 0 auto;
    	border-collapse: collapse;
    }
    #productOrder th {
    	font-weight: normal;
    	height: 21px;
    	background-color: #54A0D1;
    }
    #productOrder th.description {
    	text-align: left;
    }
    #productOrder th.price {
    	width: 25%;
    }
    #productOrder td, #productOrder th {
    	padding: 3px;
    }
    #productOrder .price {
    	text-align: center;
    	text-transform: uppercase;
    }
    #productOrder .heading {
    	font-weight: bold;
    }
    #productOrder .selection {
    	width: 62%;
    }
    #productOrder .insurance input {
    	float: right;
    }
     
    </style>
    </head>
     
    <body>
    <table id="productOrder">
      <tr>
        <th class="description" colspan="2">Description</th>
        <th class="price">PRICE</th>
      </tr>
      <tr>
        <td colspan="2">&nbsp;</td>
        <td class="price">&nbsp;</td>
      </tr>
      <tr>
        <td colspan="2" class="heading">Product Name</td>
        <td class="price heading">Free</td>
      </tr>
      <tr>
        <td class="heading">Shipping:</td>
        <td class="selection">
    	  <select name="shipping">
            <option value="4.99" selected="selected">Ground ($4.99)</option>
            <option value="8.99">Expedited ($8.99)</option>
          </select>
        </td>
        <td id="shippingPrice" class="price">$4.99</td>
      </tr>
      <tr class="insurance">
        <td>
    		<input name="insurance" type="checkbox" value="1.00" checked="checked" />
    	</td>
        <td>Yes, Please insure my order for only $1.00</td>
        <td id="insurancePrice" class="price">$1.00</td>
      </tr>
      <tr>
        <td colspan="2">&nbsp;</td>
        <td class="heading price">Total</td>
      </tr>
      <tr>
        <td colspan="2">&nbsp;</td>
        <td id="totalPrice" class="price">&nbsp;</td>
      </tr>
    </table>
    <script type="text/javascript"> 
    function updateShipping() {
    	var value = getSelectValue(this);
    	updateById('shippingPrice', toDollar(value));
    	updateTotal();
    }
    function getSelectValue(select) { 
    	return select.options[select.selectedIndex].value;
    }
    function updateInsurance() {
    	var value = getCheckedValue(this);
    	updateById('insurancePrice', toDollar(value));
    	updateTotal();
    }
    function getCheckedValue(checkbox) {
    	if (checkbox.checked) {
    		return checkbox.value;
    	}
    }
    function updateById(id, text) {
    	document.getElementById(id).innerHTML = text;
    }
    function toDollar(value){
    	value = parseFloat(value);
    	if (!Number(value)) {
    		value = 0;
    	}
        return '$' + value.toFixed(2);
    }
    function updateTotal() {
        var total = calculateTotal();
    	updateById('totalPrice', toDollar(total));
    }
    function calculateTotal() {
    	var shipping = document.getElementsByName('shipping')[0];
    	var shippingValue = getSelectValue(shipping);
    	var shippingPrice = parseFloat(shippingValue) || 0;
    	var insurance = document.getElementsByName('insurance')[0];
    	var insuranceValue = getCheckedValue(insurance);
    	var insurancePrice = parseFloat(insuranceValue) || 0;
    	return shippingPrice + insurancePrice;
    }
    document.getElementsByName('shipping')[0].onchange = updateShipping;
    document.getElementsByName('insurance')[0].onclick = updateInsurance;
    updateTotal();
    </script>
    </body>
    </html>

    Edit:


    I should also point out that the css and javascript should be kept in separate pages, and are loaded in the following manner:

    Code html4strict:
    <html>
    <head>
        <link rel="stylesheet" type="text/css" href="style.css" />
    </head>
    <body>
    ...
    <script src="script.js"> </script>
    </body>
    </html>
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  18. #18
    SitePoint Enthusiast
    Join Date
    Dec 2008
    Posts
    46
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks again, Paul.


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •