2013-07-23 63 views
0

我正在创建一个商店,其中列出了各种选项(即通过下拉菜单选择不同尺寸并通过选择单选按钮选择不同的面料)。 (看看www.searing.me/newstore)jquery onchange受事后影响?

我写了下面的代码,这样如果做出选择,价格会更新而不需要POST来这样做,从而刷新到屏幕顶部。我的问题是 - 当我“添加到购物车”时,所有价格都会随着最初选择的价格而更新。因此,从本质上讲,在第一款产品上,如果您选择“棕色和弦”选项来添加2.25美元 - 价格会因为2.25美元增加到30.00美元而变化 - 因此为32.25美元。但是,当您点击添加到购物车时 - 右侧的产品也将其价格提高了2.25美元。

我认为这与POST注册每个onchange事件有关......我不知道。我非常喜欢Jquery/Javascript的初学者,真正知道发生了什么。

脚本是:

function updatePrice(e) { 
    var product = $(e.target).closest('.product'); 
    var price = parseFloat(product.data('price')); 

    var sizePrice = parseFloat(product.find('[name=sizeSelect] :selected').data('price')); 
    if (isNaN(sizePrice)) { 
     sizePrice = 0; 
    } 

    var patternPrice = parseFloat(product.find('[name=fabric]:checked').data('price')); 
    if (isNaN(patternPrice)) { 
    patternPrice = 0; 
    } 

    var totalPrice = price + sizePrice + patternPrice; 
    product.find('.totalCost').text('$' + totalPrice.toFixed(2)); 

} 

$(document).ready(function(){ 

    $(document).on('change', '.product', updatePrice); 
} 

什么我需要做的,以防止其他所有产品更新上添加到购物车它们的价格?

编辑:首先,重要的是要注意脚本运行完美,点击提交按钮。点击按钮后,即可更新所有价格。

这里的网页脚本:

<?php 

    echo "<div><img style='padding-left:35px; float:left;' src='/images/just11stitchesbannerII.png'></div>"; 
    echo "<div style='float:right; padding-right:55px;'>"; 
    echo return_categories($dbConnection); 
    echo "</div>"; 

    if ($cart->countItems() > 0) { 
     echo '<div style="float:right; clear:left; padding-right:50px;"> 
       <a style="outline:0;" class="gallery2" href="shoppingcartdev.php"><img style="width:55px; padding-left:75px;" src="/images/scart.png"></img></a><br/> 
       <span style="font-size:.75em;">You have ' . $cart->countItems() . ' item(s) in your shopping cart.</span> 
      </div>'; 
    } 
    else { 
     echo '<div style="float:right; clear:left; padding-right:50px;"> 
       <img style="width:55px; padding-left:75px;" src="/images/scart.png"></img><br/> 
       <span style="font-size:.75em;">You have ' . $cart->countItems() . ' in your shopping cart.</span> 
      </div>'; 
    } 
    echo '<h1 style="clear:left; padding-top:5px;">Products</h1>'; 

    // Find out if page is displaying all the products or if it is being filtered 
    $testProducts = new Products(); 

    if (isset($_POST['category_submit']) && isset($_POST['categories'])) { 
     $_POST['test'] = 'FALSE'; 
     $linkArray = printFilteredProductLinks("/newstore", $dbConnection->db, $_POST['categories']); 
     $myarray = $testProducts->getSelectedOrderProducts($linkArray["order_by"], $linkArray["start"], $linkArray["display"], 1, $_POST['categories']); 
    } 
    else { 
     $_POST['test'] = 'FALSE'; 
     $linkArray = printProductLinks("/newstore", $dbConnection->db, 1); 
     $myarray = $testProducts->getOrderProducts($linkArray["order_by"], $linkArray["start"], $linkArray["display"], 1); 
    } 

    $counter = 0; 
    $i = 0; 
    $flag = 0;       // used to check if at end of table and only 1 cell for that row 
    $stepthroughitemcount =0; 
    $itemcount = count($myarray); 

    if ($itemcount % 2 == 1) { 
     $counter = floor($itemcount/2);  // If Flag = 1 then there will be one more cell to make in the final row. 
     $flag = 1; 
    } 
    else { 
     $counter = $itemcount/2; 
    } 

    // START TABLE 



    echo "<table style='margin:5px; border-spacing:5px;'>"; 


    while ($i < $counter) { 
     $tdcount = 0; 

     while ($tdcount < 2) { 
      $optionCount = 0; 
      $mySizes = new Sizes($myarray[$stepthroughitemcount]->getID()); 
      $myPatterns = new Patterns($myarray[$stepthroughitemcount]->getID()); 


      echo "<td valign='top' class='product' data-price='" . returnTotalPrice($myarray[$stepthroughitemcount]->getPrice()) . "' style='width:575px; padding-top:8px; border: 2px solid green; padding:8px; -moz-border-radius: 10px; -webkit-border-radius: 10px; border-radius: 10px; background-color: #ACBF9A;'> 
          <div style='width:175px; float:left; text-align:center;'> 
           <a style='display:inline; float:none;' class='gallery' href='/prod_pics/" . $myarray[$stepthroughitemcount]->getPictureName() . "'><img id='picture' src='/red_prod_pics/" . $myarray[$stepthroughitemcount]->getPictureName() . "'</img></a> 
           <p class='totalCost' style='text-align:center; margin-top:0px;'>$" . number_format(returnTotalPrice($myarray[$stepthroughitemcount]->getPrice()), 2) . "</p> 
           <form id='productForm' enctype='multipart/form-data' action='newstore.php' method='POST'> 

           <input type='hidden' name='product_id' value='{$myarray[$stepthroughitemcount]->getID()}' /> 
           <input type='hidden' name='product_price' value='{$myarray[$stepthroughitemcount]->getPrice()}' /> 
           <p style='font-size:.7em; border:1px solid #008000; -moz-border-radius: 10px; -webkit-border-radius: 10px; background-color: #ddf0dd; padding:2px;'>" . $myarray[$stepthroughitemcount]->getDescription() . "</p> 
           <input style='display:inline; margin-top:5px; float:none;' type='submit' name='AddCart' value='Add To Cart'/> 
          </div> 
          <div style='margin-left:10px; float:left; width:373px;'> 
           <span style='font-weight:bold;'>Sizes:</span> 
           <span style='padding-left:100px;'> 
            <select name='sizeSelect' style='width:200px; text-align:right;'>"; 
      if (isset($_POST['AddCart'])){ 
       foreach ($mySizes->getAllSizes() as $value) { 
        //echo "<option>valuesid = " . $value->getSID() . " postsizeselect = " . $_POST['sizeSelect'] . "</option>"; 
        echo   "<option " . ($value->getPSID() == $_POST['sizeSelect'] ? 'selected' : '') . " data-price='" . $value->getSPRICE() . "' value=" . $value->getPSID() . ">" . $value->getSNAME() . "&emsp; $" . number_format($value->getSPRICE(), 2) . "</option>"; 
       } 
      } 
      else { 
       foreach ($mySizes->getAllSizes() as $value) { 
        //echo $value->getSID() . ' ' . $myarray[$stepthroughitemcount]->getDefaultSize(); 
        echo   "<option " . ($value->getSID() == $myarray[$stepthroughitemcount]->getDefaultSize() ? 'selected' : '') . " data-price='" . $value->getSPRICE() . "' value=" . $value->getPSID() . ">" . $value->getSNAME() . "&emsp; $" . number_format($value->getSPRICE(), 2) . "</option>"; 
       } 
      } 
      echo     "</select> 
           </span> 
           <br/> 
           <span style='font-weight:bold;'>Fabrics & Colors:</span><br/> 
           <table> 
            <tr>"; 
      $rowcount = 0; 

      foreach ($myPatterns->getAllPatterns() as $value2) { 
       if ($rowcount % 4 == 0) { 
        echo   '</tr> 
            <tr>'; 
       } 
       echo     '<td style="float:left; width:85px; text-align:center; "> 
              <img src="/patterns/' . $value2->getPATPICTURENAME() . '" /><br/> 
              <span style="font-size:.65em; width:65px; color: #132301;">' . $value2->getPATNAME() . '</span><br/> 
              <span>$' . number_format($value2->getPATPRICE(), 2) . '</span><br/> 
              <input data-price="' . $value2->getPATPRICE() . '" type="radio" ' . ($value2->getPATID() == $myarray[$stepthroughitemcount]->getDefaultFabric() ? "checked=\'checked\'" : "") . ' name="fabric" value=' . $value2->getPPID() . ' /> 
             </td>'; 
       $rowcount +=1; 
      } 
      echo     '</tr> 
           </table> 
          </div></form> 
        </td>'; 
      $stepthroughitemcount +=1; 
      $tdcount +=1; 
     } 


     echo "</tr>"; 
     $i+=1; 

    } 
    if ($flag == 1) { 
     $mySizes = new Sizes($myarray[$stepthroughitemcount]->getID()); 
     $myPatterns = new Patterns($myarray[$stepthroughitemcount]->getID()); 
      echo "<tr> 
         <td valign='top' class='product' data-price='" . returnTotalPrice($myarray[$stepthroughitemcount]->getPrice()) . "' style='width:575px; padding-top:8px; border: 2px solid green; padding:8px; -moz-border-radius: 10px; -webkit-border-radius: 10px; border-radius: 10px; background-color: #ACBF9A;'> 
          <div style='width:175px; float:left; text-align:center;'> 
           <a style='display:inline; float:none;' class='gallery' href='/prod_pics/" . $myarray[$stepthroughitemcount]->getPictureName() . "'><img id='picture' src='/red_prod_pics/" . $myarray[$stepthroughitemcount]->getPictureName() . "'</img></a> 
           <p class='totalCost' style='text-align:center; margin-top:0px;'>$" . number_format(returnTotalPrice($myarray[$stepthroughitemcount]->getPrice()), 2) . "</p> 
           <form id='productForm' enctype='multipart/form-data' action='newstore.php' method='POST'> 
           <input style='display:inline; float:none;' type='submit' name='AddCart' value='Add To Cart'/> 
           <input type='hidden' name='product_id' value='{$myarray[$stepthroughitemcount]->getID()}' /> 
           <input type='hidden' name='product_price' value='{$myarray[$stepthroughitemcount]->getPrice()}' /> 
          </div> 
          <div style='margin-left:10px; float:left; width:373px;'> 
           <span style='font-weight:bold;'>Sizes:</span> 
           <span style='padding-left:100px;'> 
            <select name='sizeSelect' style='width:200px; text-align:right;'>"; 
      foreach ($mySizes->getAllSizes() as $value) { 
       //echo $value->getSID() . ' ' . $myarray[$stepthroughitemcount]->getDefaultSize(); 
       echo     "<option " . ($value->getSID() == $myarray[$stepthroughitemcount]->getDefaultSize() ? 'selected' : '') . " data-price='" . $value->getSPRICE() . "' value=" . $value->getPSID() . ">" . $value->getSNAME() . "&emsp; $" . number_format($value->getSPRICE(), 2) . "</option>"; 
      }       
      echo     "</select> 
           </span> 
           <br/> 
           <span style='font-weight:bold;'>Fabrics & Colors:</span><br/> 
           <table> 
            <tr>"; 
      $rowcount = 0; 

      foreach ($myPatterns->getAllPatterns() as $value2) { 
       if ($rowcount % 4 == 0) { 
        echo   '</tr> 
            <tr>'; 
       } 
       echo     '<td style="float:left; width:85px; text-align:center; "> 
              <img src="/patterns/' . $value2->getPATPICTURENAME() . '" /><br/> 
              <span style="font-size:.75em">' . $value2->getPATNAME() . '</span><br/> 
              <span>$' . number_format($value2->getPATPRICE(), 2) . '</span><br/> 
              <input data-price="' . $value2->getPATPRICE() . '" type="radio" ' . ($value2->getPATID() == $myarray[$stepthroughitemcount]->getDefaultFabric() ? "checked=\'checked\'" : "") . ' name="fabric" value=' . $value2->getPPID() . ' /> 
             </td>'; 
       $rowcount +=1; 
      } 
      echo     '</tr> 
           </table> 
          </div></form> 
        </td> 
       </tr>'; 
    } 
    echo "</table>"; 

    if (isset($_POST['category_submit']) && isset($_POST['categories'])) { 
     printFilteredProductLinks("/newstore", $dbConnection->db, $_POST['categories']); 
    } 
    else { 
     printProductLinks("/newstore", $dbConnection->db, 1); 
    } 
    echo '</body> 
     </html>'; 

?> 
+0

代码对我来说看起来很好。什么是您的产品的html结构? –

+0

有些提交/发布触发了onchange事件。我改变了按钮来输入按钮,然后写下:$('input [type = button]')。click(function(){$('form')。submit();});当我点击按钮时 - 它再次更新了所有定价。 有点 - 我需要找出一种方法来禁用触发如果提交页面的变化事件处理程序.... – user2611810

+0

好吧 - 我认为TravJenkins是正确的 - 我相信我有一个SESSION变量持有我的期权价格,它是使用它来更新所有的价格 - 让我玩一下,稍微更新一下。 – user2611810

回答

0

您可能需要只选择

$.first(); 
+0

'。最接近()'应该只返回一个结果。 – Barmar

+0

重要的是要注意 - 代码在页面提交之前工作正常。它只更新一个价格。这是提交(添加到购物车),一次更新它们。 – user2611810

1

的第一个结果,我认为你是对的,而该事件再次触发。

我想这会发生,因为你所有的提交按钮都有相同的ID,并为每篇文章调用updatePrice函数。

只要试一试,并删除提交按钮的ID。

+0

我删除了提交按钮的ID,它仍然更新所有产品的价格。 – user2611810

+0

我再次浏览了你的html代码,并且有更多的元素具有相同的id(例如表单本身)。元素ID在整个文档中应该是唯一的。那是什么课程。即使它不会解决你的实际问题,它可能会但我不能测试它,你应该总是使用ID作为独特的选择。 – hyde

+0

我欣赏评论。老实说,这是我第一次尝试PHP。那么,第二,如果你把它算作网站的第二版。最初,我设定了每个产品都与现在的选项分开。当我的妻子不止一次开始列出照片时,她可以列出几种尺寸,我意识到我需要重新审视。 说实话,我认为我在编写代码时经常会遇到id和name属性混杂在一起(在我进入事件绑定之前),或者如果我正在使用for CSS - 我同意,但我真的不认为ID是这个问题:( – user2611810

0

我怀疑这与导致另一个onChange事件的帖子有关......可能与“后端”上的某些事情有关。

如果你在onChange代码上放置一个断点,它只会在你改变输入时触发(就像你期望的那样)。另外,当您在添加到购物车后返回页面时,PHP将发送带有已更新值的HTML。另一个重要的注意事项 - 它不只是更新一个正确的更新店铺中所有商品的成本。

+0

你是对的 - 对不起 - 它更新了所有 - 我只是想指出右边的一个例子 - 谢谢你的注意。 – user2611810

+0

如果您提交没有任何其他选项的表单之一,它也会重置。这也使我不是onChange(因为这个事件永远不会被解雇)。 – TravJenkins

+0

Trav - 我相信你可能是对的 - 我会玩一些代码并回报。 – user2611810