user2611810
user2611810

Reputation: 1

jquery onchange impacted by post event?

I am creating a store where products are listed with options (ie different sizes via a drop down and different fabrics via a selection of radio buttons). (Check out www.searing.me/newstore)

I wrote the following code so that if a selection was made, the price would be updated without needing a POST to do so and thus refreshing to the top of the screen. My problem is - that when I "add to cart" then ALL prices are getting updated with the price that was initially selected.

So, in essence, on the first product, if you select the "brown chord" option to add $2.25 - the price changes by adding $2.25 to $30.00 - thus $32.25. HOWEVER, when you click add to cart - the product to the right changed ITS price by $2.25 as well.

I assume this has something to do with the POST registering another onchange event for each....I don't know. And I'm VERY MUCH a beginner with Jquery/Javascript to really know what's happening.

Script is:

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);
}

What do I need to do so as to prevent all the other products updating their price on the add to cart?

EDIT: First, Important to note that the script runs perfect up to the point that the submit button is clicked. Once the button is clicked, that is what updates ALL the prices.

Here's the page script:

<?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>';

?>

Upvotes: 0

Views: 278

Answers (3)

TravJenkins
TravJenkins

Reputation: 104

I doubt this has to do with the post causing another onChange event... probably has to do with something on the "back end".

If you put a break point on the onChange code it only fires when you are changing the inputs (like you would expect). Also, when you get the page back after adding to cart the PHP is sending back HTML with the values already updated. Another important note - it is not just updating the one to the right it is updating the cost of ALL items in the shop.

Upvotes: 0

optimisticupdate
optimisticupdate

Reputation: 1689

I think you are right and the event is triggered again.

I guess this happens because all your submit buttons have the same ID and the updatePrice function is called for each article.

Just give it a try and remove the id of the submit buttons.

Upvotes: 1

John
John

Reputation: 6268

You may need to select only the first result with

$.first();

Upvotes: 0

Related Questions