Использование change () для суммирования общей стоимости из групп переключателей - PullRequest
0 голосов
/ 30 октября 2019

Я создаю сайт заказа карточек, который выбирается с помощью групп переключателей. Я придумал это, чтобы добавить общую стоимость. Я установил, что цена базовой карты работает, но когда я добавил дополнительные расходы, по-видимому, используя ту же логику, я не могу понять, как сложить рабочую сумму.

PS - Извините за беспорядок в посте

Я добавил консольные журналы для поиска ошибок, но ни одна не отображается при прохождении процесса.

// create a variables

var selectedCardPricePer;
var cardOneQty;
var cardOneCombinedPricePer;
var cardOneSubtotal;
let paperType;
let envType;
let totalPricePer;

// Get base price based on selected card
$('input:radio[name="img-select"]').change(
    function() {
        // select the checked radio button, grab the "ratio" attribute, and save it as "selectedCardType"
        var selectedCardType = $('input:radio[name="img-select"]:checked').attr('ratio');
        console.log('selectedCardType = %s', selectedCardType);

        // BASE PRICES
        // grab the price for the price per card depending on the selected card type 
        if (selectedCardType == '5x7') {
            selectedCardPricePer = 0.10; // price per 5x7 card
        } else if (selectedCardType == '7x5') {
            selectedCardPricePer = 0.15; // price per 7x5 card
        } else if (selectedCardType == '4x8p5') {
            selectedCardPricePer = 0.00; // price per 4x8.5 calendar card
        } else if (selectedCardType == '8p5x4') {
            selectedCardPricePer = 0.00; // price per 8.5x4 calendar card
        } else {
            console.log('selectedCardType = %s', selectedCardType);
            console.log('selectedCardType does not have an associated price!');
        }

        console.log('selectedCardPricePer = %s', selectedCardPricePer);
        // "selectedCardPricePer" should be relevant per the selected card 
    }
);

// create the paper price variable
var addPricePerPaper = 0;

// paper prices
$('input:radio[name="paper-select"]').change(
    function() {
        var selectedPaper;

        // select the checked radio button, grab the "ratio" attribute, and save it as "selectedCardType"
        var selectedPaper = $('input:radio[name="paper-select"]:checked').val();
        console.log('selectedPaper = %s', selectedPaper);

        // grab the price for the price per card depending on the selected card type 
        if (selectedPaper == 'Premium Paper') {
            addPricePerPaper = 0.10; // price per premium
        } else if (selectedPaper == 'Standard Paper') {
            addPricePerPaper = 0; // price per standard
        } else {
            console.log('selectedPaper does not equal an appropriate value');
        }

        console.log('addPricePerPaper = %s', addPricePerPaper);
        // 'addPricePerPaper' should be relevant per the selected paper.
    }
);

// create the envelope price variable
var addPricePerEnvelope = 0;

// env prices
$('input:radio[name="env-select"]').change(
    function() {
        // select the checked radio button, grab the value.
        var selectedEnvelope = $('input:radio[name="env-select"]:checked').attr('material');
        console.log('selectedEnvelope = %s', selectedEnvelope);

        // grab the price for the price per card depending on the selected card type 
        if (selectedEnvelope == 'standard') {
            addPricePerEnvelope = 0; // price per 
        } else if (selectedEnvelope == 'linen') {
            addPricePerEnvelope = 0.10; // price per 
        } else if (selectedEnvelope == 'foil') {
            addPricePerEnvelope = 0.15; // price per
        } else if (selectedEnvelope == 'none') {
            addPricePerEnvelope = 0; // price per
        } else {
            console.log('selectedEnvelope did not equal an appropriate value');
        }

        console.log('addPricePerEnvelope = %s', addPricePerEnvelope);

        // addPricePerEnvelope should equal the extra price per envelope
    }
);

var addPricePerPrintedReturn = 0;

// Create the printed return price variable
$('input:checkbox[name="env-printed-return"]').change(
    function() {

        // set the variable to false first, in case it is not checked
        var checkedReturn = false;

        // check if the checkbox is checked, if so, this sets the variable to true
        checkedReturn = $('input:checkbox[name="env-printed-return"]').prop('checked');
        console.log('checkedReturn = %s', checkedReturn);

        // if the variable is true, add a price, if not, don't.
        if (checkedReturn == true) {
            addPricePerPrintedReturn = 0.05;
        } else {
            addPricePerPrintedReturn = 0;
        }
        console.log('addPricePerPrintedReturn = %s', addPricePerPrintedReturn);

        // addPricePerPrintedReturn should equal the extra price per return address addition
    }
)

/*
    Up to this point, we should have several variables set per the following:
    - selectedCardPricePer = base price per card
    - addPricePerPaper = extra price per card, for a paper option
    - addPricePerEnvelope = extra price per env, for a env option
    - addPricePerPrintedReturn = extra price to print return addresses on envs, if selected
*/

// watch qty
$('input[name="quantity-field-one"]').change(
    function () { 
        // grab the quantity
        cardOneQty = $('input[name="quantity-field-one"]').val();
    }
);


// I'll need to come back to this
$('input:radio[name="img-select"]').change(updateCardOnePricing());
$('input:radio[name="paper-select"]').change(updateCardOnePricing());
$('input:radio[name="env-select"]').change(updateCardOnePricing());
$('input:checkbox[name="env-printed-return"]').change(updateCardOnePricing());
$('input[name="quantity-field-one"]').change(updateCardOnePricing());

// Update Pricing Function
function updateCardOnePricing() {

    console.log('updateCardOnePricing triggered.');

    console.log('selectedCardPricePer = %s', selectedCardPricePer);
    console.log('addPricePerPaper = %s', addPricePerPaper);
    console.log('addPricePerEnvelope = %s', addPricePerEnvelope);
    console.log('addPricePerPrintedReturn = %s', addPricePerPrintedReturn);
    console.log('cardOneQty = %s', cardOneQty);

    // add up the total cost per card
    cardOneCombinedPricePer = selectedCardPricePer + addPricePerPaper + addPricePerEnvelope + addPricePerPrintedReturn;
    console.log('cardOneCombinedPricePer = %s', cardOneCombinedPricePer);

    // combine the quantity with price to get subtotal
    cardOneSubtotal = cardOneQty * cardOneCombinedPricePer;
    console.log('cardOneSubtotal = %s', cardOneSubtotal);

    // round to nearest tenth
    cardOneSubtotal = Number(Math.round(cardOneSubtotal+'e2')+'e-2');
    // fix deicmals to make sense for monies
    cardOneSubtotal = cardOneSubtotal.toFixed(2);

    $('#card1-subtotal').html(cardOneSubtotal);
}

///// HTML Below

<div class="radio-button">
                        <input type="radio" name="paper-select" id="paper-opt1" value="Standard Paper" checked="checked" />
                        <label material="Standard">
                            Standard paper
                        </label>
                        <div class="clearfloat"></div>
                    </div>

                    <div class="radio-button">
                        <input type="radio" name="paper-select" id="paper-opt2" value="Premium Paper" material="Premium" />
                        <label >
                        Premium (+ $0.10 per)
                        </label>
                        <div class="clearfloat"></div>
                    </div>

                    <br />

                    <span class="step-label">
                        Envelope Options
                    </span>

                    <div class="radio-button">
                        <input type="radio" name="env-select" id="env-opt1" value="No Envelope" material="none" />
                        <label >
                            No Envelope
                        </label>
                        <div class="clearfloat"></div>
                    </div>

                    <div class="radio-button">
                        <input type="radio" name="env-select" id="env-opt2" value="Standard Non-Printed Envelope" material="standard" checked="checked"/>
                        <label >
                            Standard Non-Printed Envelope (+ $0.00 per)
                        </label>
                        <div class="clearfloat"></div>
                    </div>

                    <div class="radio-button">
                        <input type="radio" name="env-select" id="env-opt3" value="Linen Envelope" material="linen"/>
                        <label >
                            Linen Envelope (+ $0.10 per)
                        </label>
                        <div class="clearfloat"></div>
                    </div>

                    <div class="radio-button">
                        <input type="radio" name="env-select" id="env-opt4" value="Foil-Lined Envelope" material="foil"/>
                        <label >
                            Foil-Lined Envelope (+ $0.15 per)
                        </label>
                        <div class="clearfloat"></div>
                    </div>

                    <div class="radio-button">
                        <input type="checkbox" name="env-printed-return" id="env-opt5" value="Printed Return Address" material="return"/>
                        <label >
                            Printed Return Address (+ $0.05 per)
                        </label>
                        <div class="clearfloat"></div>
                    </div>
                </div>

                <div class="p under">
                    <label for="quantity-field-one">
                        <span class="step-label">
                            Quantity:
                        </span>
                        <input type="number" name="quantity-field-one" id="quantity-field-one" required>
                        <div class="clearfloat"></div>
                    </label>


                    <div class="subtotal">
                        <p>
                            Price per card 
                            <strong>
                                $
                                <span id="card1-ppc">
                                    <em>Please select a card.</em>
                                </span> <!-- price per card appended here -->
                            </strong>
                        </p>
                    </div>

                    <div class="total">
                        <p>
                            Subtotal
                            <strong>
                                $
                                <span id="card1-subtotal">
                                    <em>Please enter a quantity.</em>
                                </span> <!-- price subtotal for this card appended here -->
                            </strong>
                        </p>
                    </div>

1 Ответ

0 голосов
/ 30 октября 2019

При обработке события для нескольких элементов с одинаковым именем / классом вы должны использовать ключевое слово «this» для ссылки на элемент внутри функции, в противном случае вы всегда ссылаетесь на первый элемент коллекции. У вас одинаковая проблема со всеми обработчиками событий.

В общем, это:

$('input:radio[name="img-select"]').change(
    function() {
        // select the checked radio button, grab the "ratio" attribute, and save it as "selectedCardType"
        var selectedCardType = $('input:radio[name="img-select"]:checked').attr('ratio');

должно выглядеть так:

$('input:radio[name="img-select"]').change(
    function() {
        // select the checked radio button, grab the "ratio" attribute, and save it as "selectedCardType"
        var selectedCardType = $(this).attr('ratio');

во всех ваших обработчиках событий.

Обратите внимание на использование $ (this) для ссылки на текущий элемент, а не всегда на первый.

...