На изображении я сначала установил первые два флажка и нажал кнопку расчета. Затем я снял флажок со второго и снова щелкнул мышью, чтобы рассчитать, и он все равно дал мне как значения, так и общую цену. Кроме того, когда я нажимаю кнопку «Очистить» и проверяю ее еще раз, происходит то же самое, но с ценой «0».
const calcButton = document.getElementById('calc-button');
const clearButton = document.getElementById('clear-button');
const result = document.getElementById('result');
let currentValue = 0;
let totalPrice = 0;
let exams = [];
function getCheckboxValue(event) {
const checkboxValue = event.target.value;
if (event.target.checked) {
currentValue = checkboxValue;
getPrice(currentValue);
getName(currentValue);
} else {
currentValue = '';
}
}
function getPrice() {
let price = document.querySelector(`#price${currentValue}`);
let priceText = price.textContent.replace(',', '.');
return totalPrice += parseInt(priceText, 10);
}
function getName() {
let name = document.querySelector(`#name${currentValue}`);
nameText = name.textContent.trim();
exams.push(nameText);
return exams;
}
function displayTotal() {
let examsList = exams.join("<br>")
result.style.display = "block";
result.innerHTML =
`<span>Deu <strong>${totalPrice}</strong> conto</span>
<br><br>
<span>Exames marcados:
<br>
${examsList}</span>
`;
return result;
}
function clear() {
result.innerHTML = ''
result.style.display = "none";
currentValue = 0;
totalPrice = 0;
}
const checkboxes = document.querySelectorAll('input[type = "checkbox"]');
checkboxes.forEach(checkbox => {
checkbox.addEventListener('click', getCheckboxValue);
});
calcButton.addEventListener("click", displayTotal);
clearButton.addEventListener("click", clear);
<style>
@import url('https://fonts.googleapis.com/css2?family=Michroma&display=swap');
</style>
<h1>Calculadora da Duda</h1>
<table border = "1">
<tr>
<th>Check</th>
<th>Código</th>
<th>Nome</th>
<th>Preço</th>
</tr>
<tr>
<label for = "checkbox1"></label>
<td><input type = "checkbox" name = "check" title = "check" value = "1"></td>
<td id = "code1">17HPC</td>
<td id = "name1">17 HIDROXIPROGESTERONA</td>
<td id = "price1">30,00</td>
</tr>
<tr>
<label for = "checkbox2"></label>
<td><input type = "checkbox" name = "check" title = "check" value = "2"></td>
<td id = "code2">17OHC</td>
<td id = "name2">17 HIDROXICORTICOIDES</td>
<td id = "price2">55,00</td>
</tr>
<tr>
<label for = "checkbox3"></label>
<td><input type = "checkbox" name = "check" title = "check" value = "3"></td>
<td id = "code3">17OHP</td>
<td id = "name3">17 ALFA-HIDROXIPROGESTERONA</td>
<td id = "price3">30,00</td>
</tr>
<tr>
<label for = "checkbox4"></label>
<td><input type = "checkbox" name = "check" title = "check" value = "4"></td>
<td id = "code4">5HIAC</td>
<td id = "name4">ACIDO 5 HIDROXI INDOL ACETICO</td>
<td id = "price4">90,00</td>
</tr>
<tr>
<label for = "checkbox5"></label>
<td><input type = "checkbox" name = "check" title = "check" value = "5"></td>
<td id = "code5">5NUC</td>
<td id = "name5">5 NUCLEOTIDASE</td>
<td id = "price5">130,00</td>
</tr>
<tr>
<label for = "checkbox6"></label>
<td><input type = "checkbox" name = "check" title = "check" value = "6"></td>
<td id = "code6">A1A</td>
<td id = "name6">ALFA 1 ANTI-TRIPSINA</td>
<td id = "price6">30,00</td>
</tr>
<tr>
<label for = "checkbox7"></label>
<td><input type = "checkbox" name = "check" title = "check" value = "7"></td>
<td id = "code7">A1AF</td>
<td id = "name7">ALFA 1 ANTI-TRIPSINA FECAL</td>
<td id = "price7">80,00</td>
</tr>
<tr>
<label for = "checkbox8"></label>
<td><input type = "checkbox" name = "check" title = "check" value = "8"></td>
<td id = "code8">AACH1</td>
<td id = "name8">TESTE RAPIDO CHIKUNGUNYA IGG/IGM</td>
<td id = "price8">125,00</td>
</tr>
<tr>
<label for = "checkbox9"></label>
<td><input type = "checkbox" name = "check" title = "check" value = "9"></td>
<td id = "code9">AACHI</td>
<td id = "name9">ANTICORPOS ANTI CHIKUNGUNYA IGG/IGM</td>
<td id = "price9">240,00</td>
</tr>
</table>
<div id = "final-buttons">
<button type = "button" id = "calc-button">Calcular</button>
<button type = "button" id = "clear-button">Limpar</button>
</div>
<div id = "result"></div>
Вы только сбрасываете totalPrice
и т. д. ал. при нажатии «Очистить». Похоже, вам может потребоваться перерасчет при каждом щелчке флажка, даже если он не установлен.
Похоже, ваша проблема связана с неустановленным флажком, который не влияет на общий результат и экзамены. В случае снятия отметки следует удалить эту сумму из общей стоимости и название экзамена из переменной экзаменов.
Ниже будет описано, как вам следует изменить свой код, чтобы он был правильным:
const calcButton = document.getElementById('calc-button');
const clearButton = document.getElementById('clear-button');
const result = document.getElementById('result');
let totalPrice = 0;
let exams = [];
function getCheckboxValue(event) {
const checkboxValue = event.target.value;
if (event.target.checked) {
currentValue = checkboxValue;
addPrice(currentValue);
addName(currentValue);
} else {
removePrice(checkboxValue);
removeName(checkboxValue);
}
}
function addPrice(value) {
let price = document.querySelector(`#price${value}`);
let priceText = price.textContent.replace(',', '.');
totalPrice += parseInt(priceText, 10);
}
function removePrice(value) {
let price = document.querySelector(`#price${value}`);
let priceText = price.textContent.replace(',', '.');
totalPrice -= parseInt(priceText, 10);
}
function addName(value) {
let name = document.querySelector(`#name${value}`);
let nameText = name.textContent.trim();
exams.push(nameText);
}
function removeName(value) {
let name = document.querySelector(`#name${value}`);
let nameText = name.textContent.trim();
exams = exams.filter(exam => exam !== nameText);
}
function displayTotal() {
let examsList = exams.join("<br>")
result.style.display = "block";
result.innerHTML =
`<span>Deu <strong>${totalPrice}</strong> conto</span>
<br><br>
<span>Exames marcados:
<br>
${examsList}</span>
`;
}
function clear() {
result.innerHTML = ''
result.style.display = "none";
currentValue = 0;
totalPrice = 0;
exams = [];
// Uncheck all checkboxes
document.querySelectorAll('input[type = "checkbox"]').forEach(checkbox => checkbox.checked = false);
}
const checkboxes = document.querySelectorAll('input[type = "checkbox"]');
checkboxes.forEach(checkbox => {
checkbox.addEventListener('click', getCheckboxValue);
});
calcButton.addEventListener("click", displayTotal);
clearButton.addEventListener("click", clear);
<style>
@import url('https://fonts.googleapis.com/css2?family=Michroma&display=swap');
</style>
<h1>Calculadora da Duda</h1>
<table border = "1">
<tr>
<th>Check</th>
<th>Código</th>
<th>Nome</th>
<th>Preço</th>
</tr>
<tr>
<label for = "checkbox1"></label>
<td><input type = "checkbox" name = "check" title = "check" value = "1"></td>
<td id = "code1">17HPC</td>
<td id = "name1">17 HIDROXIPROGESTERONA</td>
<td id = "price1">30,00</td>
</tr>
<tr>
<label for = "checkbox2"></label>
<td><input type = "checkbox" name = "check" title = "check" value = "2"></td>
<td id = "code2">17OHC</td>
<td id = "name2">17 HIDROXICORTICOIDES</td>
<td id = "price2">55,00</td>
</tr>
<tr>
<label for = "checkbox3"></label>
<td><input type = "checkbox" name = "check" title = "check" value = "3"></td>
<td id = "code3">17OHP</td>
<td id = "name3">17 ALFA-HIDROXIPROGESTERONA</td>
<td id = "price3">30,00</td>
</tr>
<tr>
<label for = "checkbox4"></label>
<td><input type = "checkbox" name = "check" title = "check" value = "4"></td>
<td id = "code4">5HIAC</td>
<td id = "name4">ACIDO 5 HIDROXI INDOL ACETICO</td>
<td id = "price4">90,00</td>
</tr>
<tr>
<label for = "checkbox5"></label>
<td><input type = "checkbox" name = "check" title = "check" value = "5"></td>
<td id = "code5">5NUC</td>
<td id = "name5">5 NUCLEOTIDASE</td>
<td id = "price5">130,00</td>
</tr>
<tr>
<label for = "checkbox6"></label>
<td><input type = "checkbox" name = "check" title = "check" value = "6"></td>
<td id = "code6">A1A</td>
<td id = "name6">ALFA 1 ANTI-TRIPSINA</td>
<td id = "price6">30,00</td>
</tr>
<tr>
<label for = "checkbox7"></label>
<td><input type = "checkbox" name = "check" title = "check" value = "7"></td>
<td id = "code7">A1AF</td>
<td id = "name7">ALFA 1 ANTI-TRIPSINA FECAL</td>
<td id = "price7">80,00</td>
</tr>
<tr>
<label for = "checkbox8"></label>
<td><input type = "checkbox" name = "check" title = "check" value = "8"></td>
<td id = "code8">AACH1</td>
<td id = "name8">TESTE RAPIDO CHIKUNGUNYA IGG/IGM</td>
<td id = "price8">125,00</td>
</tr>
<tr>
<label for = "checkbox9"></label>
<td><input type = "checkbox" name = "check" title = "check" value = "9"></td>
<td id = "code9">AACHI</td>
<td id = "name9">ANTICORPOS ANTI CHIKUNGUNYA IGG/IGM</td>
<td id = "price9">240,00</td>
</tr>
</table>
<div id = "final-buttons">
<button type = "button" id = "calc-button">Calcular</button>
<button type = "button" id = "clear-button">Limpar</button>
</div>
<div id = "result"></div>
Я попробую это! Большое спасибо
Я попробовал, функция очистки сработала отлично! А вот проблема в том, чтобы поставить 2 галочки, посчитать, снять одну и снова посчитать. Я заметил, что это сработало, когда я использовал значение в качестве параметра для функций удаления и checkboxValue вместо currentValue. Можешь мне сказать почему? Я даже полностью удалил переменную currentValue, и она работала идеально.
Основная проблема с вашим кодом связана с тем, что вы не обрабатываете отмену флажков для удаления значений, а добавляете новые только при их проверке.
Вы можете решить проблему, упростить свой код и улучшить его качество, изменив шаблон, чтобы вычислять только итоговые значения и обновлять DOM при нажатии кнопки «Рассчитать», вместо того, чтобы пытаться сохранить промежуточный итог при взаимодействии с флажками. Для этого вы можете получить отмеченные флажки из DOM и просмотреть их, как показано в примере ниже.
Также обратите внимание, что вы можете внести несколько дополнительных настроек:
label
. Они вообще не отображаются, поскольку вы поместили их за пределы структуры table
, поэтому они избыточны и их можно удалить.id
. Это просто усложняет ваш код, его сложнее поддерживать и легче взломать. Вместо этого используйте общие атрибуты class
и связывайте контент вместе, используя методы обхода DOM.const checkboxes = [...document.querySelectorAll('input[type = "checkbox"]')];
const calcButton = document.querySelector('#calc-button');
const clearButton = document.querySelector('#clear-button');
const result = document.querySelector('#result');
function displayTotal() {
let totalPrice = 0;
let examsList = [];
checkboxes.filter(cb => cb.checked).forEach(cb => {
const row = cb.closest('tr');
totalPrice += parseInt(row.querySelector('.price').textContent.replace(',', '.'), 10);
examsList.push(row.querySelector('.name').textContent);
});
result.style.display = "block";
result.innerHTML = `<span>Deu <strong>${totalPrice}</strong> conto</span><br><br><span>Exames marcados:<br>${examsList.join('<br />')}</span>`;
return result;
}
function clear() {
result.innerHTML = ''
result.style.display = "none";
currentValue = 0;
totalPrice = 0;
}
calcButton.addEventListener("click", displayTotal);
clearButton.addEventListener("click", clear);
<style>
@import url('https://fonts.googleapis.com/css2?family=Michroma&display=swap');
</style>
<h1>Calculadora da Duda</h1>
<table border = "1">
<tr>
<th>Check</th>
<th>Código</th>
<th>Nome</th>
<th>Preço</th>
</tr>
<tr>
<td><input type = "checkbox" name = "check" title = "check" value = "1"></td>
<td class = "code">17HPC</td>
<td class = "name">17 HIDROXIPROGESTERONA</td>
<td class = "price">30,00</td>
</tr>
<tr>
<td><input type = "checkbox" name = "check" title = "check" value = "2"></td>
<td class = "code">17OHC</td>
<td class = "name">17 HIDROXICORTICOIDES</td>
<td class = "price">55,00</td>
</tr>
<tr>
<td><input type = "checkbox" name = "check" title = "check" value = "3"></td>
<td class = "code">17OHP</td>
<td class = "name">17 ALFA-HIDROXIPROGESTERONA</td>
<td class = "price">30,00</td>
</tr>
<tr>
<td><input type = "checkbox" name = "check" title = "check" value = "4"></td>
<td class = "code">5HIAC</td>
<td class = "name">ACIDO 5 HIDROXI INDOL ACETICO</td>
<td class = "price">90,00</td>
</tr>
<tr>
<td><input type = "checkbox" name = "check" title = "check" value = "5"></td>
<td class = "code">5NUC</td>
<td class = "name">5 NUCLEOTIDASE</td>
<td class = "price">130,00</td>
</tr>
<tr>
<td><input type = "checkbox" name = "check" title = "check" value = "6"></td>
<td class = "code">A1A</td>
<td class = "name">ALFA 1 ANTI-TRIPSINA</td>
<td class = "price">30,00</td>
</tr>
<tr>
<td><input type = "checkbox" name = "check" title = "check" value = "7"></td>
<td class = "code">A1AF</td>
<td class = "name">ALFA 1 ANTI-TRIPSINA FECAL</td>
<td class = "price">80,00</td>
</tr>
<tr>
<td><input type = "checkbox" name = "check" title = "check" value = "8"></td>
<td class = "code">AACH1</td>
<td class = "name">TESTE RAPIDO CHIKUNGUNYA IGG/IGM</td>
<td class = "price">125,00</td>
</tr>
<tr>
<td><input type = "checkbox" name = "check" title = "check" value = "9"></td>
<td class = "code">AACHI</td>
<td class = "name">ANTICORPOS ANTI CHIKUNGUNYA IGG/IGM</td>
<td class = "price">240,00</td>
</tr>
</table>
<div id = "final-buttons">
<button type = "button" id = "calc-button">Calcular</button>
<button type = "button" id = "clear-button">Limpar</button>
</div>
<div id = "result"></div>
Большое спасибо! Я обязательно попробую это. Также спасибо за замечание по поводу этикеток и идентификаторов, меня они тоже смутили, но я проигнорировал это. Будучи новичком, я не изучил множество элементов.
Предпочитаю работать таким образом, используя только одну функцию для очистки и вычисления суммы (computeSum()
) в этом коде:
const
calcButton = document.getElementById('calc-button')
, clearButton = document.getElementById('clear-button')
, result = document.getElementById('result')
, myTableBody = document.querySelector('#my-table tbody')
, ES_Nums = new Intl.NumberFormat('es-ES', { minimumFractionDigits: 2 })
, rowsTable =
[ { cod: '17HPC', Nome: '17 HIDROXIPROGESTERONA', Preço: 30.00 }
, { cod: '17OHC', Nome: '17 HIDROXICORTICOIDES', Preço: 55.00 }
, { cod: '17OHP', Nome: '17 ALFA-HIDROXIPROGESTERONA', Preço: 30.00 }
, { cod: '5HIAC', Nome: 'ACIDO 5 HIDROXI INDOL ACETICO', Preço: 90.00 }
, { cod: '5NUC', Nome: '5 NUCLEOTIDASE', Preço: 130.00 }
, { cod: 'A1A', Nome: 'ALFA 1 ANTI-TRIPSINA', Preço: 30.00 }
, { cod: 'A1AF', Nome: 'ALFA 1 ANTI-TRIPSINA FECAL', Preço: 80.00 }
, { cod: 'AACH1', Nome: 'TESTE RAPIDO CHIKUNGUNYA IGG/IGM', Preço: 125.00 }
, { cod: 'AACHI', Nome: 'ANTICORPOS ANTI CHIKUNGUNYA IGG/IGM', Preço: 240.00 }
];
rowsTable.forEach( (row,indx) =>
{
let tr = myTableBody.insertRow();
tr.insertCell().innerHTML = `<input type = "checkbox" title = "check mi" value = "${indx}">`;
tr.insertCell().textContent = row.cod;
tr.insertCell().textContent = row.Nome;
tr.insertCell().textContent = ES_Nums.format( row.Preço);
});
myTableBody.addEventListener('click', e =>
{
let chkBx = e.target.closest('tr').querySelector('input[type = "checkbox"]')
chkBx.checked = !chkBx.checked;
})
calcButton.addEventListener('click', computeSum )
;
clearButton.addEventListener('click', e =>
{
myTableBody.querySelectorAll('input[type = "checkbox"]:checked').forEach( chkBx => chkBx.checked = false );
computeSum();
})
function computeSum()
{
result.textContent = ''; // clear content
let
total = 0
, xRow = [];
;
myTableBody.querySelectorAll('input[type = "checkbox"]:checked').forEach( chkBx =>
{
total += rowsTable[ chkBx.value ].Preço;
xRow.push(+chkBx.value);
});
if (xRow.length === 0) return
;
result.innerHTML = `
<span>Deu <strong>${ES_Nums.format(total)}</strong> conto</span>
<br><br>
<span>Exames marcados:
<br>
${ xRow.map( n => rowsTable[n].Nome).join('<br>')}
</span>`;
}
body {
font-family : Arial, Helvetica, sans-serif;
font-size : 14px;
}
table {
background : darkblue;
border-collapse : separate;
border-spacing : 1px;
margin-bottom : .8em;
}
table caption {
font-size : 1.4rem;
font-weight : bold;
padding : .4em 0;
}
th {
background-color : #7fccff;
padding : .4em .6em ;
}
tr {
--bgTdColor : whitesmoke;
}
td {
background-color : var(--bgTdColor);
padding : .4em;
text-align : center;
}
td:last-of-type {
text-align : right;
}
tr:hover {
cursor : pointer;
--bgTdColor : orange;
}
td input[type = "checkbox"] { /* let it be only clicked on row action */
pointer-events: none;
}
<table id = "my-table">
<caption>Calculadora da Duda</caption>
<thead>
<tr><th>Check</th><th>Código</th><th>Nome</th><th>Preço</th></tr>
</thead>
<tbody>
</tbody>
</table>
<div id = "final-buttons">
<button type = "button" id = "calc-button">Calcular</button>
<button type = "button" id = "clear-button">Limpar</button>
</div>
<div id = "result"></div>
Спасибо! Но я не знаю, будет ли работать этот массив таблицы, потому что я добавлю к нему 500 или более TD, заметьте, я конвертирую 12-страничный список PDF. Но это очень умный способ сделать это
Пожалуйста, включите соответствующий HTML-код.