Hello to all.
There is a table of goods with several values. The price is taken from the cell with class = "price"
In addition, there are cells with display: none and the classes price_50, price_100, price_500, price_1000, price_2500
It is necessary to implement it so that when inputting in input the quantity> = 50, the price was taken from the cell with class = "price_50" ,
when entering> = 100 from a cell with class = "price_100" ,
when entering> = 500 from a cell with class = "price_500" ,
when entering> = 1000 from the cell with class = "price_1000" ,
when entering> = 2500 from cell with class = "price_2500"
those. so that the price changes dynamically depending on the entered value in the "quantity" cell.
Also, those lines in which the value of the cell "non-zero" must be output in <p class="output-all"></p> that is, output all the cells of a given row into one row.
Thank you all in advance.
Sample table
https://jsfiddle.net/v8wh4sLh/
- oneI did not understand about the output-all. Can you explain in more detail? - dmitryshishkin
- there is <p class = "output-all"> </ p> it needs to output all the lines with a value in input more than 0, for example, so Goods> CHAB> ABS. Black colour. > Quantity 5> Price 99> Amount 495 - Dumb
- oneCan you give a sample code of what should fall in output-all? - dmitryshishkin
- oneAnd another such question. When we have quantity from 50 to 100, then we hide the cell with the price and display price_100? - dmitryshishkin
- oneSo, understood. Now I will write a solution. - dmitryshishkin
|
1 answer
I allowed myself to remake some things in the structure of HTML and thought out some things in JS that were not described.
So there will be less load on the DOM and it is easier to work with values. Well, to expand the whole thing, too. In principle, it was possible to break into smaller functions, but I did not.
var calculator = { parent: document.getElementById('table-price-box'), totalPrice: 0, position: [], isText: false, init: function() { var self = this; this.parent.addEventListener('input', function(e) { var field = e.target, tr = field.parentElement.parentElement; // Пересчитываем стоимость в этом поле self.changeInput(field, tr); // Пересчитываем всё self.recount(); }); }, // Пересчет одного поля changeInput: function(field, tr) { var price = tr.querySelector('.price'), num = parseInt(field.value); // Если ввели не число, то ничего не меням if(!isNaN(num)) { var count = this.getCount(price, num), result; // Считаем итоговую цену result = count * num; // Если у нас в качестве цены за единицу текстовое значение, то не будем ничго выводить if(isNaN(result)) { tr.querySelector('.sum').textContent = ''; } // В противном случае вывведем цену else { // Но сначала округляем число result = Math.round(result); // Выводим tr.querySelector('.sum').textContent = result; } // Меняем отображаемую стоимость за единицу price.textContent = count; } }, // Получаем стоимость единицы товара в зависимости от позиции getCount: function(price, num) { var count; if(num < 50) count = price.dataset.price0; if(num >= 50 && num < 100) count = price.dataset.price50; if(num >= 100 && num < 500) count = price.dataset.price100; if(num >= 500 && num < 1000) count = price.dataset.price500; if(num >= 1000 && num < 2500) count = price.dataset.price1000; if(num >= 2500) count = price.dataset.price2500; return count; }, // Пересчитываем весь калькулятор recount: function() { var self = this, tr = this.parent.querySelectorAll('tr'); // Обнуляем общую сумму, позиции и текстовые суммы self.totalPrice = 0; self.positions = []; self.isText = false; tr.forEach(function(item) { var field = item.querySelector('input'); // Проверяем есть ли в строке инпут if(field) { var num = field.value; // Дополниельно проверяем количество на "не число" if(!isNaN(num) && num > 0) { var price = item.querySelector('.price').textContent; // Проверяем есть ли у нас стоимость за единицу в значении if(isNaN(+price)) { self.isText = true; } else { // Увеличиваем общую стоимость self.totalPrice += parseFloat(item.querySelector('.sum').textContent); } // Добавляем позиции self.positions.push({ classificator: item.querySelector('.calc-classificator').textContent, properties: item.querySelector('.calc-properties').textContent, price: price, num: num, sum: item.querySelector('.sum').textContent }); } } }); self.setNewResult(); }, // Устанавливаем новые результаты setNewResult: function() { var self = this, sum = self.totalPrice; // Если у нас есть текстовое значение, то добавляем плюсик if(self.isText) sum += '+'; self.parent.querySelector('#total').textContent = sum; // Выводим добавленные позиции var str = ''; self.positions.forEach(function(pos) { str += '<div style="margin-bottom: 5px">'; str += 'Классификатор:' + pos.classificator + ' '; str += 'Свойства:' + pos.properties + ' '; str += 'Цена:' + pos.price + ' '; str += 'Кол-во:' + pos.num + ' '; str += 'Сумма:' + pos.sum + ' '; str += '</div>'; }); self.parent.querySelector('.output-all').innerHTML = str; } }; calculator.init(); <link href="https://netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css" rel="stylesheet"/> <link href="https://netdna.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <script src="https://netdna.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script> <table id="table-price-box" class="table table-hover table-bordered table-condensed"> <thead> <tr> <td colspan="6"> <div class="col-md-6"> <p style="font-size:20px;margin:5px 0;">Общая сумма заказа <span id="total">0</span> руб</p> </div> <div class="col-md-6"> <p class="output-all"></p> </div> </td> </tr> <tr> <td align="center" width="30%"> <p align="center">Наименование</p> </td> <td align="center" width="10%"> <p align="center">Классификатор материала</p> </td> <td align="center" width="30%"> <p align="center">Основные свойства материала</p> </td> <td align="center" width="10%"> <p align="center">Количество</p> </td> <td align="center" width="10%"> <p align="center">Цена, руб</p> </td> <td align="center" width="10%"> <p align="center">Итого, руб</p> </td> </tr> </thead> <tbody> <tr class="td-box"> <td align="center" rowspan="5" valign="middle"><a href="#">Товар</a><br/> <p>Габаритные размеры<br/>65x36x14 мм</p> <p align="center"><img src="https://dummyimage.com/250x250/99cccc.gif" class="price-img"/></p> </td> <td align="center" class="calc-classificator">ЧАБ</td> <td align="center" class="calc-properties">АБС. Цвет: черный.</td> <td align="center"> <input min="0" type="number" style="border-radius:5px;width:80%;"/> </td> <td align="center" data-price0="99" data-price50="84" data-price100="74.6" data-price500="67.2" data-price1000="61.6" data-price2500="догов." class="price">99</td> <td align="center" class="sum"></td> </tr> <tr class="td-box"> <td align="center" class="calc-classificator"> ССА ТСА </td> <td align="center" class="calc-properties">АБС. Цвет: светло-серый; темно-серый.</td> <td align="center"> <input min="0" type="number" style="border-radius:5px;width:80%;"/> </td> <td align="center" data-price0="106" data-price50="89.2" data-price100="79.4" data-price500="71.4" data-price1000="65.4" data-price2500="догов." class="price">106</td> <td align="center" class="sum"></td> </tr> <tr class="td-box"> <td align="center" class="calc-classificator">ЧАББ</td> <td align="center" class="calc-properties">АБС с повышенным блеском. Цвет: черный.</td> <td align="center"> <input min="0" type="number" style="border-radius:5px;width:80%;"/> </td> <td align="center" data-price0="102" data-price50="86.6" data-price100="77" data-price500="69.2" data-price1000="63.4" data-price2500="догов." class="price">102</td> <td align="center" class="sum"></td> </tr> <tr class="td-box"> <td align="center" class="calc-classificator"> ССАБ ТСАБ </td> <td align="center" class="calc-properties">АБС с повышенным блеском. Цвет: светло-серый; темно-серый.</td> <td align="center"> <input min="0" type="number" style="border-radius:5px;width:80%;"/> </td> <td align="center" data-price0="104" data-price50="87.8" data-price100="78" data-price500="70.2" data-price1000="64.4" data-price2500="догов." class="price">104</td> <td align="center" class="sum"></td> </tr> <tr class="td-box"> <td align="center" class="calc-classificator">Латунь</td> <td align="center" class="calc-properties">Покрытие - никель</td> <td align="center"> <input min="0" type="number" style="border-radius:5px;width:80%;"/> </td> <td align="center" data-price0="54" data-price50="45.2" data-price100="40.2" data-price500="36.2" data-price1000="33.2" data-price2500="догов." class="price">54</td> <td align="center" class="sum"></td> </tr> </tbody> </table> - It is written here to avoid comments in the spirit of "thank you", but I thank you anyway, now I'm into hop and I can not test your decision. How to get to the computer, I will definitely check and unsubscribe. Thanks again! - Dumb
- Yes, everything works fine, but I have a couple more questions. How to make that in the output-all also added the text of the link (product) from the first column? Is it possible to do so that output-all is displayed not in the table, but in an arbitrary place on the page (to be attached not to the class, but to the id) - Dumb
|