Еще более короткий путь - назначить имя сигнала функции в аргументах ключевого слова конструктора, например. QDial(valueChanged=spinbox.setValue)
. PyQt автоматически подключит сигнал valueChanged()
к spinbox.setValue()
.
Исходя из нашего обсуждения в комментариях, я предложил другое решение вашей проблемы.
Вместо создания новой таблицы каждый раз, когда выбирается категория (и с использованием локального хранилища), вы можете отобразить все данные категории в таблице, а затем скрыть и показать строки таблицы в зависимости от того, какая категория выбрана.
Это будет означать, что любые количественные значения, выбранные пользователем, останутся в полях ввода (даже при изменении категории), поскольку поле ввода останется в DOM.
Сначала вам нужно будет добавить имя категории к каждому элементу в вашем JSON, т.е.
{ "Item Code": "1056", "Item Name": "banana shake", "category name": "juce"}
Затем, когда таблица генерируется (в функции addTable
), вы добавляете класс с именем [ 117], а также класс, равный "category name"
в JSON (таким образом, производя теги tr аналогично следующему формату):
<tr class="item-row juce">
Примечание: это так, что мы можем нацеливать определенные строки на динамически добавлять стили.
Когда выбрана новая категория, вы можете динамически добавлять стили к соответствующим строкам. Стиль, который мы можем использовать для скрытия и отображения строк таблицы, является свойством видимости, которое мы можем установить либо видимым (чтобы показать строку), либо свернутым (чтобы скрыть строку).
element.style.visibility = "visible";
ИЛИ
element.style.visibility = "collapse";
Итак, учитывая все это, ваш код будет выглядеть следующим образом (я прокомментировал, где я добавил код):
function addTable(tableData) {
var col = Object.keys(tableData[0]);
var countNum = col.filter(i => !isNaN(i)).length;
var num = col.splice(0, countNum);
col = col.concat(num);
var table = document.createElement("table");
var tr = table.insertRow(-1); // TABLE ROW.
var colNum = col.length; //to improve the speed
for (var i = 0; i < colNum + 1; i++) {
var th = document.createElement("th"); // TABLE HEADER.
if (i >= colNum) {
th.innerHTML = "Quantity";
tr.appendChild(th);
tr.classList.add("text-center");
tr.classList.add("head")
} else {
th.innerHTML = col[i];
tr.appendChild(th);
tr.classList.add("text-center");
tr.classList.add("head")
}
}
for (var i = 0; i < tableData.length; i++) {
tr = table.insertRow(-1);
//add a class called "item-row" to the table row so that we can target all item rows
tr.classList.add("item-row");
for (var j = 0; j < col.length + 1; j++) {
//add a class with the name of the category to each items row. This will be either juce, rice or roti etc.
var categoryName = tableData[i]["category name"];
tr.classList.add(categoryName);
let tabCell = tr.insertCell(-1);
var hiddenField = document.createElement("input");
hiddenField.style.display = "none";
var tabledata = tableData[i][col[j]];
if (i > -1 && j >= colNum) {
var quantityField = document.createElement("input");
quantityField.style.border = "none";
quantityField.style["text-align"] = "center";
quantityField.setAttribute('name', 'Quantity');
quantityField.setAttribute('autocomplete', 'on');
quantityField.setAttribute('value', '0');
quantityField.setAttribute('type', 'number');
quantityField.setAttribute('required', 'required');
quantityField.classList.add("dataReset");
tabCell.appendChild(quantityField);
} else {
if (tableData[i]['Item Code'] === tableData[i][col[j]]) {
tabCell.innerHTML = tabledata;
hiddenField.setAttribute('name', 'Item_Code');
hiddenField.setAttribute('value', tabledata);
tabCell.appendChild(hiddenField);
}
if (tableData[i]['Item Name'] === tableData[i][col[j]]) {
tabCell.innerHTML = tabledata;
hiddenField.setAttribute('name', 'Item_Name');
hiddenField.setAttribute('value', tabledata);
tabCell.appendChild(hiddenField);
}
if (j > 1)
tabCell.classList.add("text-right");
}
}
}
var divContainer = document.getElementById("HourlysalesSummary");
divContainer.innerHTML = "";
divContainer.appendChild(table);
table.classList.add("table");
table.classList.add("table-striped");
table.classList.add("table-bordered");
table.classList.add("table-hover");
}
$('#CategoryName').on('change', function() {
var selectedOption = this.value;
console.log(selectedOption);
//get all item rows so we can target them.
var itemRows = document.getElementsByClassName("item-row");
if(selectedOption === 'All'){
//If "All" then style all rows with visibility: visible.
for(var i = 0; i < itemRows.length; i++){
itemRows[i].style.visibility = "visible";
}
}else{
//If the selectedOption is anything other than "All",
//we firstly style all rows with visibility: collapse
for(var i = 0; i < itemRows.length; i++){
itemRows[i].style.visibility = "collapse";
}
//we then get all rows which have the selectedOption as a class and style those rows with visibility: visible.
var selectedItemRows = document.getElementsByClassName(selectedOption);
for(var i = 0; i < selectedItemRows.length; i++){
selectedItemRows[i].style.visibility = "visible";
}
}
});
Вы можете использовать локальное хранилище для хранения пары ключ / значение.
Пары ключ / значение будут оставаться в браузере до тех пор, пока вы не удалите их (т.е. с помощью localStorage.clear()
).
Вот идея о том, как вы могли бы использовать его в своем проекте.
id="Qty1056"
. (1056 код товара). Затем, прежде чем установить для атрибута «значение» значение 0 (например, quantityField.setAttribute('value', '0');
), вы проверяете локальное хранилище, чтобы увидеть, сохранено ли там значение с момента последнего изменения пользователем количества для этого элемента. (Если в локальном хранилище нет значения, установите значение количества в 0. Если значение существует в локальном хранилище для этого кода изделия, получите значение и установите для него значение поля ввода количества.) Я добавил мой новый код в ваш полный код. Код, который я добавил, помечен комментарием //ADDING NEW CODE
и другими комментариями.
Кроме того, вы можете проверить, что в localStorage
, посетив вкладку Application
в Developer tools
(я прикрепил скриншот ниже кода).
$(document).ready(function() {
//clear local storage. (Note: if you want the values to persist after u refresh browser then you should NOT clear local storage).
localStorage.clear();
//the rest of your (document).ready code goes here as normal
});
//Your addTable function. (It's mostly the same as you had. I've added comments where i've added code)
function addTable(tableData) {
var col = Object.keys(tableData[0]);
var countNum = col.filter(i => !isNaN(i)).length;
var num = col.splice(0, countNum);
col = col.concat(num);
var table = document.createElement("table");
var tr = table.insertRow(-1); // TABLE ROW.
var colNum = col.length; //to improve the speed
for (var i = 0; i < colNum + 1; i++) {
var th = document.createElement("th"); // TABLE HEADER.
if (i >= colNum) {
th.innerHTML = "Quantity";
tr.appendChild(th);
tr.classList.add("text-center");
tr.classList.add("head")
} else {
th.innerHTML = col[i];
tr.appendChild(th);
tr.classList.add("text-center");
tr.classList.add("head")
}
}
for (var i = 0; i < tableData.length; i++) {
tr = table.insertRow(-1);
for (var j = 0; j < col.length + 1; j++) {
let tabCell = tr.insertCell(-1);
var hiddenField = document.createElement("input");
hiddenField.style.display = "none";
var tabledata = tableData[i][col[j]];
if (i > -1 && j >= colNum) {
var quantityField = document.createElement("input");
quantityField.style.border = "none";
quantityField.style["text-align"] = "center";
quantityField.setAttribute('name', 'Quantity');
quantityField.setAttribute('autocomplete', 'on');
quantityField.setAttribute('type', 'number');
quantityField.setAttribute('required', 'required');
quantityField.classList.add("dataReset");
//ADDING CODE HERE
//create a unique Id string for the quantity input field.
//We will use a string e.g 'Qty' concantenated with the item code for this item (as it is unique).
//So we will have something like 'Qty1056'
var quantityIdString = 'Qty' + tableData[i]['Item Code'];
//add the id attribute to the input field
quantityField.setAttribute('id', quantityIdString);
//check localStorage to see if a quantity value exists for this item code
//the key will be something like 'Qty1056' (the same as the id of the quantity input field).
if(localStorage.getItem(quantityIdString) === null){
//this key does NOT exist in local storage
//therefore the user has not changed the value of this items quantity input field yet so set it to 0.
quantityField.setAttribute('value', '0');
}else{
//this key DOES exist in local storage so get the value from local storage and
//set the value attribute of our quantity input field to it
var quantityFromLocalStorage = localStorage.getItem(quantityIdString);
quantityField.setAttribute('value', quantityFromLocalStorage);
}
//append the quantity field to the table cell
tabCell.appendChild(quantityField);
} else {
if (tableData[i]['Item Code'] === tableData[i][col[j]]) {
tabCell.innerHTML = tabledata;
hiddenField.setAttribute('name', 'Item_Code');
hiddenField.setAttribute('value', tabledata);
tabCell.appendChild(hiddenField);
}
if (tableData[i]['Item Name'] === tableData[i][col[j]]) {
tabCell.innerHTML = tabledata;
hiddenField.setAttribute('name', 'Item_Name');
hiddenField.setAttribute('value', tabledata);
tabCell.appendChild(hiddenField);
}
if (j > 1)
tabCell.classList.add("text-right");
}
}
}
var divContainer = document.getElementById("HourlysalesSummary");
divContainer.innerHTML = "";
divContainer.appendChild(table);
table.classList.add("table");
table.classList.add("table-striped");
table.classList.add("table-bordered");
table.classList.add("table-hover");
//ADDING CODE HERE
//Now that the table has been appended to the document we can add the listeners to the quantity input fields as follows.
for (var i = 0; i < tableData.length; i++) {
///log the item code to check it
console.log(tableData[i]['Item Code']);
//pass in the item code to the addQuantityFieldListener function
addQuantityFieldListener(tableData[i]['Item Code']);
}
}
//ADDING CODE HERE
function addQuantityFieldListener(itemCode){
/* This function adds an "input" listener to a quantity input field to check when a new quantity value
* is selected/entered by the user for a particular item.
* Each time a new quantity is selected/entered we store the new value in local storage.
*/
//form the quantityIdString which will also be the key of the item in local storage
var quantityIdString = 'Qty' + itemCode;
var quantityInputField = document.getElementById(quantityIdString);
//we listen for the "input" event which will occur when a new quantity value is selected/entered by the user on this quantity input field.
quantityInputField.addEventListener("input", function(){
//store the most recent quantity value for this item in local storage as follows:
localStorage.setItem(quantityIdString, quantityInputField.value);
});
}