D
D
dgallyamshin2020-11-20 15:12:13
css
dgallyamshin, 2020-11-20 15:12:13

How to write a shipping calculator with a drop down list of cities?

There is courier delivery. She has her own tariffs in different zones of the country. Delivery from one zone to another is calculated by the sum of the tariffs of these two zones. There are two drop-down lists with the choice of the city, in short, these are two select:
1. The locality where the parcel was sent. (here, for example, 20 cities)
2. Locality for receiving the parcel. (and here)
Task:
We need a script that:
1. Will compare the city selected in the first input with the cities specified in .... case: ... brake
And will set the cost depending on the first city.
2. Will compare the city selected in the second input with the cities specified in .... case: ... brake
And will set the cost depending on the second city.
3. Will add up the cost of tariffs in these cities and display this value in some div.
4. If the tariff of these cities is the same, then it will not add them up, but simply display the first value.

Here is the code, but there is one select, but you need two, and instead of div input.

<form action="" id="checkout-form">
  <select name="" id="order-fld-4">
  <option value="Санкт-Петербург">Санкт-Петербург</option>
  <option value="Москва">Москва</option>
  <option value="Казань">Санкт-Петербург</option>
</select>
<input type="text" name="custom_delivery_tax">
</form>

// обработчик изменения выпадающего списка
$('#order-fld-4').on('change', function(){
    // получаем город, который выбрал пользователь
    var city = $(this).val();
    // запускаем нашу функцию и передаем в нее город
    myCalculator(city);
});
// Функция расчета и записи стоимости доставки
function myCalculator(city){
    var cost;

    // Сопоставляем выбранные город и цену
    switch(city){
      case 'Москва': cost = 100; break;
      case 'Санкт-Петербург': cost = 200; break;
      case 'Казань': cost = 300; break;
      default: cost = 500;   
   }

   // если поле custom_delivery_tax не существует       
   if($('input[name="custom_delivery_tax"]').length == 0){  
     // добавить его
     $('#checkout-form').append('<input type="hidden" name="custom_delivery_tax" value="0">');
   }
   // запись стоимости доставки в поле
   custom_delivery_tax$('input[name="custom_delivery_tax"]').val(cost);
}

https://jsfiddle.net/8Lrhxbne/

The code doesn't want to work for some reason!

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dmitry, 2020-11-20
@DKWLB

You have an error on the very last line.
And jquery was not added to the fiddle,
this is how it works

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question