• Najnowsze pytania
  • Bez odpowiedzi
  • Zadaj pytanie
  • Kategorie
  • Tagi
  • Zdobyte punkty
  • Ekipa ninja
  • IRC
  • FAQ
  • Regulamin
  • Książki warte uwagi

Kalkulator w formularzu - JavaScript

Aruba Cloud - Virtual Private Server VPS
0 głosów
496 wizyt
pytanie zadane 18 listopada 2021 w JavaScript przez DLFDL Początkujący (270 p.)

Próbuje napisać kod, który pomnożyłby cenę produktu przez ilość tego produktu w formularzu. Jak na razie wygląda to tak, będę wdzięczny za komentarze.

<form id="myForm" name="myForm" method="post" action="MAILTO:x211xxx824@xxxx.xx">
        <input type="text" id="username" name="username" placeholder="Username">
        <input type="password" id="password" name="password" placeholder="Password" maxlength="11">
        <select id="size" onchange="calculateTotal()">
          <option value="Please choose your size.">Size</option>
          <option value="Good choice :)
          Price - €5.00">Large</option>
          <option value="Perfect choice :)
          Price - €7.50">Extra-Large</option>
          <option value="Attention !!
          Portion size matters.
          A balanced diet is not only about eating the right kinds
          of foods but also about consuming them in the right amounts.
          Larger portions may encourage over consumption,
          which, in turn, may lead to weight gain.
          Price - €17.00">Supersize</option>
        </select>
        <input type="number" id="quantity" name="quantity" placeholder="Quantity" min="1" max="100" onchange="calculateTotal()">
        <input type="text" id="promo" name="promo" placeholder="Promo Code">
        <input type="text" id="totalPrice" name="totalPrice" value="" placeholder="Total Price">
        <textarea name="name" rows="15" cols="60" placeholder="Additional comment..." onfocus="this.placeholder=''" onblur="this.placeholder='Additional comment...'"></textarea>
        <input type="submit" name="Order" value="Place order">
        <input type="reset" name="Reset" value="Reset">
      </form>
var theForm = document.forms["myForm"];

    var size_prices = new Array();
    size_prices["Please choose your size."] = 0;
    size_prices["Good choice :) Price - €5.00"] = 5;
    size_prices["Perfect choice :) Price - €7.50"] = 7.5;
    size_prices["Attention"] = 17;

    function getSizePrice() {
      var burritoSizePrice = 0;
      var theForm = document.forms["myForm"];
      var selectedSize = theForm.elements["size"];
      burritoSizePrice = size_prices[selectedSize.value];
      return burritoSizePrice;
    }

    function getQuantity() {
      var theForm = document.forms["myForm"];
      var quantity = theForm.elements["quantity"];
      var howmany = 0;
      if (quantity.value != "") {
        howmany = parseInt(quantity.value);
      }
      return howmany;
    }

    function getTotal() {
      var burritoPrice = getSizePrice() * getQuantity();

      document.getElementById('totalPrice').innerHTML = burritoPrice;

    }

 

1 odpowiedź

0 głosów
odpowiedź 18 listopada 2021 przez qax Dyskutant (8,060 p.)
edycja 19 listopada 2021 przez qax

Nie powinno się używać w atrybutach value tak dziwacznych nazw - to samo tyczy się kluczy w tablicach asocjacyjnych.

Działające rozwiązanie:

var sizePrices = [];
sizePrices.push(['Please choose your size.', 0]);
sizePrices.push(['Good choice :) Price - €5.00', 5]);
sizePrices.push(['Perfect choice :) Price - €7.50', 7.5]);
sizePrices.push(['Attention !! Portion size matters. A balanced diet is not only about eating the right kinds of foods but also about consuming them in the right amounts. Larger portions may encourage over consumption, which, in turn, may lead to weight gain. Price - €17.00', 17]);
 
function calculate() {
    let quantity = document.forms['myForm'].elements['quantity'].value;
    let size = document.forms['myForm'].elements['size'].value;
    let output = document.getElementById('output');
    if (quantity && size) {
        output.innerHTML = sizePrices[size][0] + '<br />total price - €' + (parseFloat(quantity) * parseFloat(sizePrices[size][1]));
    } else {
        output.innerHTML = 'Incorrect data!'
    }
}
<form id="myForm" name="myForm">
<select id="size">
<option value="0">Size</option>
<option value="1">Large</option>
<option value="2">Extra-Large</option>
<option value="3">Supersize</option>
</select>
<input type="number" id="quantity" placeholder="Quantity" min="1" max="100">
<button type="button" onclick="calculate()">Oblicz</button>
</form>
<span id="output"></span>

 

komentarz 21 listopada 2021 przez DLFDL Początkujący (270 p.)

dziękuje bardzo, czy istnieje jakiś prosty sposób żeby dodać 13.5% zniżki po wpisaniu konkretnego hasła (string) w konkretne pole znajdujace sie w tym samym formularzu?

<input type="text" id="promo" name="promo" placeholder="Discount Code">

 

komentarz 21 listopada 2021 przez qax Dyskutant (8,060 p.)

Oczywiście, że się da smiley. Jednak weryfikację kodów rabatowych należy robić wyłącznie po stronie back-endu, ponieważ kod po stronie klienta jest jawny i każdy może go sobie odczytać. W każdym bądź razie przedstawiam sposób dodania zniżki po wpisaniu hasła topsecret:

<form id="myForm" name="myForm">
<select id="size">
<option value="0">Size</option>
<option value="1">Large</option>
<option value="2">Extra-Large</option>
<option value="3">Supersize</option>
</select>
<input type="number" id="quantity" placeholder="Quantity" min="1" max="100">
<input type="text" id="promo" name="promo" placeholder="Discount Code">
<button type="button" onclick="calculate()">Oblicz</button>
</form>
<span id="output"></span>
var sizePrices = [];
sizePrices.push(['Please choose your size.', 0]);
sizePrices.push(['Good choice :) Price - €5.00', 5]);
sizePrices.push(['Perfect choice :) Price - €7.50', 7.5]);
sizePrices.push(['Attention !! Portion size matters. A balanced diet is not only about eating the right kinds of foods but also about consuming them in the right amounts. Larger portions may encourage over consumption, which, in turn, may lead to weight gain. Price - €17.00', 17]);
  
function calculate() {
    let quantity = document.forms['myForm'].elements['quantity'].value;
    let size = document.forms['myForm'].elements['size'].value;
    let output = document.getElementById('output');
    let promo = document.getElementById('promo');
    let discount = 13.5;
    let correctcode = 'topsecret';
    if (quantity && size) {
    if (promo.value == correctcode) {
        output.innerHTML = sizePrices[size][0]
        + '<br />Discount - ' + discount
        + '%<br />Total price - €' + (parseFloat(quantity) * parseFloat(sizePrices[size][1])) + ' with ' + discount + '% discount = €' + ((parseFloat(quantity) * parseFloat(sizePrices[size][1])) - (parseFloat(quantity) * parseFloat(sizePrices[size][1])) * (discount / 100)).toFixed(2);
    	} else {
      	output.innerHTML = sizePrices[size][0]
        + '<br />Discount - none<br />Total price - €' + (parseFloat(quantity) * parseFloat(sizePrices[size][1])).toFixed(2);
      }
    } else {
        output.innerHTML = 'Incorrect data!'
    }
}

 

Podobne pytania

0 głosów
2 odpowiedzi 1,084 wizyt
pytanie zadane 17 kwietnia 2017 w PHP przez Kamil Czech Dyskutant (7,700 p.)
0 głosów
2 odpowiedzi 6,719 wizyt
0 głosów
2 odpowiedzi 301 wizyt
pytanie zadane 17 kwietnia 2019 w JavaScript przez chakip Nowicjusz (210 p.)

93,331 zapytań

142,323 odpowiedzi

322,400 komentarzy

62,664 pasjonatów

Motyw:

Akcja Pajacyk

Pajacyk od wielu lat dożywia dzieci. Pomóż klikając w zielony brzuszek na stronie. Dziękujemy! ♡

Oto polecana książka warta uwagi.
Pełną listę książek znajdziesz tutaj

Wprowadzenie do ITsec, tom 1 Wprowadzenie do ITsec, tom 2

Można już zamawiać dwa tomy książek o ITsec pt. "Wprowadzenie do bezpieczeństwa IT" - mamy dla Was kod: pasja (użyjcie go w koszyku), dzięki któremu uzyskamy aż 15% zniżki! Dziękujemy ekipie Sekuraka za fajny rabat dla naszej Społeczności!

...