Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 10 of 10
  1. #1
    New to the CF scene
    Join Date
    Dec 2011
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Post How do I auto update price when a user changes options to an item?

    Let me start by saying I am not the best in JavaScript, so any help would be much appreciated. What i am trying to do is allow a user to get a quote on how much an item would be if they wanted to sell it. all the data is being generated dynamically on the item and passed to this JavaScript correctly. The issue is when a user changes his mind and switches his options a few times the price goes out of wack and some times will actually be more then the original price. For example. If the item was in mint condition it would be 100 dollars. If it is "
    good condition" then it would loose lets say 20 percent, so it would be worth 80 dollars. Now each item has 3 sections of questions, what is the condition of the item, any "modifiers" like water damage or functional issues, and then third section is if its missing any parts or cables. All of this is being asked on 1 page, and when a user changes any of the options it should update the price on that page with out the user needing to press update.
    So condition goes, 100%, 70%, 40%, 20%. Modifiers are 50 percent of current price of item, so if it was "perfect (yes I know an item cant be perfect and have water damage but this is just an example) thus being 100 dollars, and has water damage, that would make it now worth 50 dollars, and has functional issues, now worth 25 dollars. If it was missing cables, it would loose lets say 5 dollars so now its worth 20 dollars. Thats an example on how i calculate the value of the items. So once again, the actual amount is being passed correctly to this script, but when you make to many changes its not happy.



    Here is the java code I have.

    Code:
    function calculateTotal(inputItem,amount1,percent1) {
    
      with (inputItem.form) {
        // Process each of the different input types in the form.
    
        if (inputItem.type == "radio") {   // Process radio buttons.
          // Subtract the previously selected radio button value from the total.
    
          if (inputItem.name =="conditions")
    	  {
    
    		if (percent1 ==100)
    		{
    			amount2= (amount1*percent1/100)-1;
    		}
    		if (percent1 ==70)
    		{
    			amount2 = (amount1*percent1/100)-2;
    		}
    		if (percent1 ==40)
    		{
    			amount2 = (amount1*percent1/100)-3;
    		}
    		if (percent1 ==20)
    		{
    			amount2 = (amount1*percent1/100)-4;
    		}
    		calculatedTotal.value = eval(amount2) ;
    		
    
    
    	  }
          // Save the current radio selection value.
          previouslySelectedRadioButton.value = eval(inputItem.value);
    
          // Add the current radio button selection value to the total.
          calculatedTotal.value = eval(calculatedTotal.value) + eval(inputItem.value);
        } else {   // Process check boxes.
          if (inputItem.checked == false) {   // Item was unchecked. Subtract item value from total.
           	   
    	  if (inputItem.name =="modifiers1")
    	  calculatedTotal.value = eval(calculatedTotal.value) / eval(percent1/100);
         if (inputItem.name =="modifiers2")
    	  calculatedTotal.value = eval(calculatedTotal.value) / eval(percent1/100);
         if (inputItem.name =="extra1")
    	  calculatedTotal.value =  eval(calculatedTotal.value) + eval(percent1) ;
         if (inputItem.name =="extra2")
    	  calculatedTotal.value = eval(calculatedTotal.value) + eval(percent1)  ;
         if (inputItem.name =="extra3")
    	  calculatedTotal.value = eval(calculatedTotal.value) + eval(percent1);
         if (inputItem.name =="extra4")
    	  calculatedTotal.value = eval(calculatedTotal.value) + eval(percent1) ;	
    	    
    	   } else {   // Item was checked. Add the item value to the total.
         
    	 if (inputItem.name =="modifiers1")
    	  calculatedTotal.value = eval(calculatedTotal.value) *  eval(percent1/100);
         if (inputItem.name =="modifiers2")
    	  calculatedTotal.value = eval(calculatedTotal.value) *  eval(percent1/100);
         if (inputItem.name =="extra1")
    	  calculatedTotal.value = eval(calculatedTotal.value) - eval(percent1);
         if (inputItem.name =="extra2")
    	  calculatedTotal.value = eval(calculatedTotal.value) - eval(percent1);
         if (inputItem.name =="extra3")
    	  calculatedTotal.value = eval(calculatedTotal.value) - eval(percent1);
         if (inputItem.name =="extra4")
    	  calculatedTotal.value = eval(calculatedTotal.value) - eval(percent1);
    
    
          }
        }
    
        // Total value should never be less than 0.
        if (calculatedTotal.value < 0) {
          InitForm();
        }
    
        // Return total value.
       
        return(formatCurrency(calculatedTotal.value));
      }
    }
    
    // Format a value as currency.
    function formatCurrency(num) {
      num = num.toString().replace(/\$|\,/g,'');
      if(isNaN(num))
         num = "0";
      sign = (num == (num = Math.abs(num)));
      num = Math.floor(num*100+0.50000000001);
      cents = num%100;
      num = Math.floor(num/100).toString();
      if(cents<10)
          cents = "0" + cents;
      for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
          num = num.substring(0,num.length-(4*i+3)) + ',' + num.substring(num.length-(4*i+3));
      return (((sign)?'':'-') + '$' + num + '.' + cents);
    }
    
    // This function initialzes all the form elements to default values.
    function InitForm() {
      // Reset values on form.
      document.selectionForm.total.value='$0';
      document.selectionForm.calculatedTotal.value=0;
      document.selectionForm.previouslySelectedRadioButton.value=0;
    
      // Set all checkboxes and radio buttons on form to unchecked.
      for (i=0; i < document.selectionForm.elements.length; i++) {
        if (document.selectionForm.elements[i].type == 'checkbox' | document.selectionForm.elements[i].type == 'radio') {
          document.selectionForm.elements[i].checked = false;
        }
      }
    }
    
    
    
    <!-- Paste this code into the HEAD section of your HTML document
       
    </script>
    Any help would be greatly appreciated.
    Last edited by VIPStephan; 12-22-2011 at 04:30 PM. Reason: fixed closing code BB tag

  • #2
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,109
    Thanks
    38
    Thanked 498 Times in 492 Posts
    Do you have the HTML portion that is being controlled by the JS in earlier post?

  • #3
    New to the CF scene
    Join Date
    Dec 2011
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I didnt post it because its pretty crazy.... but here you go.


    [CODE]

    $query= "SELECT * FROM products WHERE products_id = '".$id."' ";

    $result = mysql_query($query) or die(mysql_error());

    $arr_table_result=mysql_fetch_full_result_array($result);


    foreach ($arr_table_result as $row)

    {
    $mainprice = $row['price'];

    $item1 = $item1 +1;
    if ($item1 ==1 )
    {
    ?> <tr><td> <?
    }
    if ($item1 >1 )
    {
    ?> <td> <?
    }

    $query= "SELECT * FROM files WHERE belongs_key = '".$row['products_id']."' and belongs_table ='products' ";

    $result = mysql_query($query) or die(mysql_error());

    $arr_table_result=mysql_fetch_full_result_array($result);

    foreach ($arr_table_result as $row2)
    {
    $linki = $row2['name'];
    }

    $query= "SELECT * FROM files WHERE belongs_key = '".$row['categories_fk']."' and belongs_table ='categories' ";

    $result = mysql_query($query) or die(mysql_error());

    $arr_table_result=mysql_fetch_full_result_array($result);

    foreach ($arr_table_result as $row3)
    {
    $linkc = $row3['name'];
    $query= "SELECT * FROM categories WHERE categories_id = '".$row['categories_fk']."' ";

    $result = mysql_query($query) or die(mysql_error());

    $arr_table_result=mysql_fetch_full_result_array($result);
    foreach ($arr_table_result as $row31)
    {

    $namec = $row31['name'];

    }
    }
    $brand1 = $row['brands_fk'];
    $query= "SELECT * FROM files WHERE belongs_key = '".$row['brands_fk']."' and belongs_table ='brands' ";

    $result = mysql_query($query) or die(mysql_error());

    $arr_table_result=mysql_fetch_full_result_array($result);

    foreach ($arr_table_result as $row4)
    {
    $linkb = $row4['name'];

    $query= "SELECT * FROM brands WHERE brands_id = '".$row['brands_fk']."' ";

    $result = mysql_query($query) or die(mysql_error());

    $arr_table_result=mysql_fetch_full_result_array($result);
    foreach ($arr_table_result as $row41)
    {

    $nameb = $row41['name'];

    }
    }

    $price = $row['price'];



    if ($_POST['conditions'] !="")
    {
    $query= "SELECT * FROM conditions WHERE conditions_id = '".$_POST['conditions']."' ";

    $result = mysql_query($query) or die(mysql_error());

    $arr_table_result=mysql_fetch_full_result_array($result);
    foreach ($arr_table_result as $condtion1)
    {

    $cond = $condtion1['percent'];

    $price = ($cond/100) * $price;
    $price = sprintf("%01.2f", $price);
    }
    }

    if ($_POST['modifiers1'] !="")
    {
    $query= "SELECT * FROM modifiers WHERE modifiers_id = '".$_POST['modifiers1']."' ";

    $result = mysql_query($query) or die(mysql_error());

    $arr_table_result=mysql_fetch_full_result_array($result);
    foreach ($arr_table_result as $mofidier)
    {

    $modi = $mofidier['percent'];

    $price = ($modi/100) * $price;
    $price = sprintf("%01.2f", $price);
    }
    }

    if ($_POST['modifiers2'] !="")
    {
    $query= "SELECT * FROM modifiers WHERE modifiers_id = '".$_POST['modifiers2']."' ";

    $result = mysql_query($query) or die(mysql_error());

    $arr_table_result=mysql_fetch_full_result_array($result);
    foreach ($arr_table_result as $mofidier)
    {

    $modi = $mofidier['percent'];

    $price = ($modi/100) * $price;
    $price = sprintf("%01.2f", $price);
    }
    }


    if ($_POST['extra1'] !="")
    {
    $query= "SELECT * FROM extras WHERE extras_id = '".$_POST['extra1']."' ";

    $result = mysql_query($query) or die(mysql_error());

    $arr_table_result=mysql_fetch_full_result_array($result);
    foreach ($arr_table_result as $extra22)
    {

    $extra = $extra22['price'];

    $price = $price - $extra;
    $price = sprintf("%01.2f", $price);
    }
    }


    if ($_POST['extra2'] !="")
    {
    $query= "SELECT * FROM extras WHERE extras_id = '".$_POST['extra2']."' ";

    $result = mysql_query($query) or die(mysql_error());

    $arr_table_result=mysql_fetch_full_result_array($result);
    foreach ($arr_table_result as $extra22)
    {

    $extra = $extra22['price'];

    $price = $price - $extra;
    $price = sprintf("%01.2f", $price);
    }
    }

    if ($_POST['extra3'] !="")
    {
    $query= "SELECT * FROM extras WHERE extras_id = '".$_POST['extra3']."' ";

    $result = mysql_query($query) or die(mysql_error());

    $arr_table_result=mysql_fetch_full_result_array($result);
    foreach ($arr_table_result as $extra22)
    {

    $extra = $extra22['price'];

    $price = $price - $extra;
    $price = sprintf("%01.2f", $price);
    }
    }

    if ($_POST['extra4'] !="")
    {
    $query= "SELECT * FROM extras WHERE extras_id = '".$_POST['extra4']."' ";

    $result = mysql_query($query) or die(mysql_error());

    $arr_table_result=mysql_fetch_full_result_array($result);
    foreach ($arr_table_result as $extra22)
    {

    $extra = $extra22['price'];

    $price = $price - $extra;
    $price = sprintf("%01.2f", $price);
    }
    }
    $price = sprintf("%01.2f", $price);
    ?>

    <table width = "100%">
    <tr><td><div class="image"><img src="uploads/categories/thumb1_<?= $linkc ?>"></div><br>
    <h4>Category: <a href="index.php?page=search&cat=<?= $row['categories_fk'] ?>"><?= $namec ?></a></h4></td><td>
    <div class="image"><img src="uploads/brands/thumb0_<?= $linkb ?>"></div><br>
    <h4>Brand: <a href="index.php?page=search&brand=<?= $brand1 ?>"><?= $nameb ?></a></h4></td>
    <td align = "right"> <img src="uploads/products/thumb1_<?= $linki ?>" /><br>
    <strong><? echo $row['name']; ?></strong></td>
    </tr>
    </table>




    <table width = "100%">
    <tr><td>

    <form action="index.php?page=box&id=<?=$id ?>" method="post" style="padding:0px;margin:0px" onsubmit=''>

    <input type="hidden" name="product_id" value="<?=$id ?>">
    <h4>Customize your item</h4></td> <td align = "right">Original Trade in Price: $<?= $mainprice;?><br />Modified Price: <strong><input type="text" name="total" readonly onFocus="this.blur();">
    </strong> <br>


    <input type="hidden" name="calculatedTotal" value="0 ">
    <input type="hidden" name="previouslySelectedRadioButton" value="0">

    </td></tr>

    <table width = "100%">
    <div>
    <tr><td width = "30%"> <?
    $query= "SELECT * FROM conditions ";

    $result = mysql_query($query) or die(mysql_error());

    $arr_table_result=mysql_fetch_full_result_array($result);


    ?><table width = "150px">
    <?
    foreach ($arr_table_result as $condition)

    {
    ?>
    <tr><td align = "left" width = "10px"><input type="radio" name="conditions" value="<?=$condition['conditions_id']?>" class="hide_price"
    onclick="this.form.total.value=calculateTotal(this,<?= $mainprice;?>,<?=$condition['percent']?>);"
    <? if ($_POST['conditions'] == $condition['conditions_id']) echo "CHECKED" ?>>

    </td>
    <td align = "left" width = "140px"><strong><?=$condition['name']?></strong><br>

    <p><?=$condition['description']?><br><br></td></tr>

    <?
    }
    ?>
    </table>

    </td><td width = "5%"></td>
    <td>
    <td width = "30%"> <?
    $query= "SELECT * FROM modifiers ";

    $result = mysql_query($query) or die(mysql_error());

    $arr_table_result=mysql_fetch_full_result_array($result);


    ?><table width = "150px">
    <?
    $modi = 0;
    foreach ($arr_table_result as $modifiers)

    { $modi = $modi+1;

    if ( $modi == 1)
    $mname1 = "modifiers1";
    if ( $modi == 2)
    $mname1 = "modifiers2";
    ?>
    <tr> <td align = "left" width = "10px">
    <input type="checkbox" name="<?=$mname1?>" value="<?=$modifiers['modifiers_id']?>" class="hide_price"
    onclick="this.form.total.value=calculateTotal(this,<?= $row['price'];?>,<?=$modifiers['percent']?>);"

    <? if ($_POST[$mname1] == $modifiers['modifiers_id']) echo "checked" ?>>

    </td>
    <td align = "left" width = "140px"><strong><?=$modifiers['name']?></strong><br>

    <p><?=$modifiers['description']?><br><br></td></tr>

    <?
    }
    ?>
    </table>


    </td><td width = "5%"></td><td>

    <td width = "30%"> <?
    $query= "SELECT * FROM products_extras where products_fk = '".$id."' ";

    $result = mysql_query($query) or die(mysql_error());

    $arr_table_result=mysql_fetch_full_result_array($result);

    $extra2 = 0;
    ?><table width = "150px">
    <?
    foreach ($arr_table_result as $extras)

    {
    $extra2 = $extra2 +1;

    if ( $extra2 == 1)
    $ename1 = "extra1";
    if ( $extra2 == 2)
    $ename1 = "extra2";
    if ( $extra2 == 3)
    $ename1 = "extra3";
    if ( $extra2 == 4)
    $ename1 = "extra4";


    $query= "SELECT * FROM extras where extras_id = '".$extras['extras_fk']."' ";

    $result = mysql_query($query) or die(mysql_error());

    $arr_table_result=mysql_fetch_full_result_array($result);
    foreach ($arr_table_result as $extras1)

    {
    $ename = $extras1['name'];

    }

    ?>
    <tr> <td align = "left" width = "10px">
    <input type="checkbox" name="<?=$ename1?>" value="<?=$extras1['extras_id']?>" class="hide_price"
    onclick="this.form.total.value=calculateTotal(this,<?=$extras1['extras_id']?>,<?=$extras1['price']?>);"

    <? if ($_POST[$ename1] == $extras1['extras_id']) echo "checked" ?>>

    </td>
    <td align = "left" width = "140px"><strong><?=$ename?></strong></td></tr>

    <?
    }
    ?>




    </td><td>
    </td></td>

    </div>



    </table>
    </div>

    </table>
    </table>
    <table width ="70%"><tr align = "right"><td> <input class='form_button' type='submit' name='submit' value='Add to Box'></td></tr></table>

    <?




    }

    [CODE]
    Last edited by dukeman911; 12-22-2011 at 05:05 PM. Reason: fixing code issue

  • #4
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,109
    Thanks
    38
    Thanked 498 Times in 492 Posts

    Arrow

    I'm not a big jQuery or PHP or SQL (or whatever) user, so I'll look at that last post later.

    In the meantime, here are some changes to the JS that might make it a bit easier to read
    as well as compact the execution a bit more. (Untested at this time)
    Code:
    <!DOC HTML>
    <html>
    <head>
    <title> Untitled </title>
    function calculateTotal(inputItem,amount1,percent1) {
    
      var amount2, percent1 calcTotal;  // really should be initialized to default values
    
      with (inputItem.form) {
    // Process each of the different input types in the form.
    
        if (inputItem.type == "radio") {   // Process radio buttons.
    // Subtract the previously selected radio button value from the total.
    
          if (inputItem.name =="conditions") {
            amount2 = amount1*percent1/100;    // forces amount2 to be something
    	if (percent1 == 100) { amount2 -= 1; }
    	if (percent1 ==  70) { amount2 -= 2; }
    	if (percent1 ==  40) { amount2 -= 3; }
    	if (percent1 ==  20) { amount2 -= 4; }
    	calculatedTotal.value = eval(amount2); // use forced value of amount2
          }
    // Save the current radio selection value.
          previouslySelectedRadioButton.value = eval(inputItem.value);
    
    // Add the current radio button selection value to the total.
          calculatedTotal.value = eval(calculatedTotal.value) + eval(inputItem.value);
    
        } else {   // Process check boxes.
          calcTotal = eval(calculatedTotal.value);  
          if (inputItem.checked == false) {   // Item was unchecked. Subtract item value from total.
           	 
            if (inputItem.name =="modifiers1") calcTotal /= eval(percent1/100);
            if (inputItem.name =="modifiers2") calcTotal /= eval(percent1/100);
            if (inputItem.name =="extra1") calcTotal += eval(percent1) ;
            if (inputItem.name =="extra2") calcTotal += eval(percent1)  ;
            if (inputItem.name =="extra3") calcTotal += eval(percent1);
            if (inputItem.name =="extra4") calcTotal += eval(percent1) ;	
    	    
          } else {   // Item was checked. Add the item value to the total.
         
    	 if (inputItem.name =="modifiers1") calcTotal *= eval(percent1/100);
             if (inputItem.name =="modifiers2") calcTotal *= eval(percent1/100);
             if (inputItem.name =="extra1") calcTotal -= eval(percent1);
             if (inputItem.name =="extra2") calcTotal -= eval(percent1);
             if (inputItem.name =="extra3") calcTotal -= eval(percent1);
             if (inputItem.name =="extra4") calcTotal -= eval(percent1);
          }
          calculatedTotal.value = calcTotal;
        }
    
    // Total value should never be less than 0.
        if (calculatedTotal.value < 0) { InitForm(); }
    
    // Return total value.
        return(formatCurrency(calculatedTotal.value));
      }
    }
    
    // Format a value as currency.
    function formatCurrency(num) {
      num = num.toString().replace(/\$|\,/g,'');
      if(isNaN(num)) num = "0";
      sign = (num == (num = Math.abs(num)));
      num = Math.floor(num*100+0.50000000001);
      cents = num%100;
      num = Math.floor(num/100).toString();
      if(cents<10) cents = "0" + cents;
      for (var i = 0; i < Math.floor((num.length-(1+i))/3); i++)
          num = num.substring(0,num.length-(4*i+3)) + ',' + num.substring(num.length-(4*i+3));
      return (((sign)?'':'-') + '$' + num + '.' + cents);
    }
    
    // This function initialzes all the form elements to default values.
    function InitForm() {
    // Reset values on form.
      document.selectionForm.total.value='$0';
      document.selectionForm.calculatedTotal.value=0;
      document.selectionForm.previouslySelectedRadioButton.value=0;
    
    // Set all checkboxes and radio buttons on form to unchecked.
      for (i=0; i < document.selectionForm.elements.length; i++) {
        if (document.selectionForm.elements[i].type == 'checkbox'
          || document.selectionForm.elements[i].type == 'radio') {
            document.selectionForm.elements[i].checked = false;
        }
      }
    }
    
    
    
    <!-- Paste this code into the HEAD section of your HTML document
       
    </script>
    </head>
    <body>
    
    </body>
    </html>
    For the formatCurrency function you might be able to get by with...
    Code:
    function formatCurrency(num) {
      return num.toFixed(2);
    }
    But that won't put in the ',' delimiters. Might want to use a regex for that.

    Good Luck!
    Last edited by jmrker; 12-22-2011 at 05:26 PM.

  • #5
    New to the CF scene
    Join Date
    Dec 2011
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts
    I tried that, and no luck, still same glitch, when you select the first options for each it works fine, but when you ...
    Select Perfect condition, sets price correctly
    Selects has water damage, sets price to half amount - correct,
    Change to "good condition" it resets the value back to as tho the water damage is not checked off even though it is, then if you uncheck water damage it is now double the amount.

    So for some reason when you select a modifier then change a condition it will ignore the modifier and just reset the value.

    Thoughts?

  • #6
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,109
    Thanks
    38
    Thanked 498 Times in 492 Posts
    I have read somewhere that the 'with...' statement may be buggy at times.
    You might try expanding that for the elements that use it and remove the 'with...' statements altogether.

  • #7
    Supreme Master coder! Philip M's Avatar
    Join Date
    Jun 2002
    Location
    London, England
    Posts
    18,159
    Thanks
    203
    Thanked 2,549 Times in 2,527 Posts
    Quote Originally Posted by jmrker View Post
    I have read somewhere that the 'with...' statement may be buggy at times.
    You might try expanding that for the elements that use it and remove the 'with...' statements altogether.
    The with statement is deprecated and should be avoided.
    And get rid of eval().

    All the code given in this post has been tested and is intended to address the question asked.
    Unless stated otherwise it is not just a demonstration.

  • #8
    New to the CF scene
    Join Date
    Dec 2011
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts
    So I think the java may be the wrong way of doing it, is there a way to auto refresh when a user selects an option? I can have the php run the code " if option X = y then do blah. PHP im fine in, java not so much...

    -- Also i tried to remove the with, and it wouldn't show any number now, and when i removed the eval's all the math when out of wack :-(
    Last edited by dukeman911; 12-22-2011 at 08:13 PM. Reason: added more info

  • #9
    Senior Coder jmrker's Avatar
    Join Date
    Aug 2006
    Location
    FL
    Posts
    3,109
    Thanks
    38
    Thanked 498 Times in 492 Posts

    Exclamation

    Quote Originally Posted by dukeman911 View Post
    So I think the java may be the wrong way of doing it, is there a way to auto refresh when a user selects an option? I can have the php run the code " if option X = y then do blah. PHP im fine in, java not so much...

    -- Also i tried to remove the with, and it wouldn't show any number now, and when i removed the eval's all the math when out of wack :-(
    Post the code you are currently testing.
    1. You are executing JavaScript, not Java. Four letters the same, but that's about it.
    2. You cannot just remove the 'with' without replacing it with the correct document reference.
    3. You cannot just remove the 'eval' and expect it to work without possible modification.

    As far as I can tell, javascript is totally acceptable for this task, you just have yet to implement it correctly.

  • #10
    New to the CF scene
    Join Date
    Dec 2011
    Posts
    5
    Thanks
    0
    Thanked 0 Times in 0 Posts
    The code is above, nothing has changed yet.


  •  

    Posting Permissions

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