Я пытаюсь вычислить в Javascript.
Я хочу знать сумму положительных и отрицательных значений.
Скрипт работает, когда я использую только одно текстовое поле.
Если значение первого текстового поля положительное, сценарий помещает значение в текстовое поле «положительное». Если значение второго текстового поля отрицательное, сценарий помещает все значения в текстовое поле «отрицательное».
Пример:
Первое текстовое поле: 50+ Второе текстовое поле: 50 -
Итого +: (пустой)
Всего -: 100
Я хочу следующее: Первое текстовое поле: 50+ Второе текстовое поле: 50 -
Итого +: 50
Всего -: 50
Я использую следующий сценарий
HTML:
Price 1:<br />
<input type = "text" id = "p1" name = "p[]">
<select id = "pn1" name = "pn[]">
<option value = "0"></option>
<option value = "1">+</option>
<option value = "2">-</option>
</select>
<br />
Price 2:<br />
<input type = "text" id = "p2" name = "p[]">
<select id = "pn2" name = "pn[]">
<option value = "0"></option>
<option value = "1">+</option>
<option value = "2">-</option>
</select>
<br />
Price 3:<br />
<input type = "text" id = "p3" name = "p[]">
<select id = "pn3" name = "pn[]">
<option value = "0"></option>
<option value = "1">+</option>
<option value = "2">-</option>
</select>
<br /><br />
Total +:<br />
<input type = "text" id = "positive" name = "positive">
<br />
Total -:<br />
<input type = "text" id = "negative" name = "negative">
<br />
Javascript:
<script>
$(document).on('change', '[name^=pn]', function selectQuantity(selectedValue){
var e = document.getElementsByName('pn[]');
var quantity = e.options[e.selectedIndex].value;
if ( quantity==='0') {
document.getElementById('positive').value = "";
document.getElementById('negative').value = "";
} else if ( quantity==='1') {
document.getElementById('positive').value = "";
document.getElementById('negative').value = "";
var numVal1 = Number(document.getElementsByName("p[]").value);
var totalValue1 = numVal1
let total = 0;
for(const el of document.getElementsByName("p[]"))
total += +el.value;
document.getElementById("positive").value = total.toFixed(2);
} else {
document.getElementById("positive").value = "";
document.getElementById("negative").value = "";
var numVal2 = Number(document.getElementsByName("p[]").value);
var totalValue2 = numVal2
let total = 0;
for(const el of document.getElementsByName("p[]"))
total += +el.value;
document.getElementById("positive").value = total.toFixed(2);
}
});
</script>
Кто-нибудь знает, почему мой скрипт не работает должным образом?



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Это кодирует беспорядок и плохую организацию, это может быть то, что вы ищете:
$('[name^=pn]').on('change', function() {
let neg = 0
let pos = 0
$('[name^=pn]').each( function( i, e) {
var quantity = e.options[e.selectedIndex].value;
if ( quantity==='0') {
} else if ( quantity==='1') {
var num = Number( document.getElementById( $(this).data('target')).value);
pos += num;
} else {
var num = Number(this.value);
neg += num;
}
});
document.getElementById('positive').value = pos;
document.getElementById('negative').value = neg;
});<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Price 1:<br />
<input type = "text" id = "p1" name = "p[]">
<select id = "pn1" name = "pn[]" data-target = "p1">
<option value = "0"></option>
<option value = "1">+</option>
<option value = "2">-</option>
</select>
<br />
Price 2:<br />
<input type = "text" id = "p2" name = "p[]">
<select id = "pn2" name = "pn[]" data-target = "p2">
<option value = "0"></option>
<option value = "1">+</option>
<option value = "2">-</option>
</select>
<br />
Price 3:<br />
<input type = "text" id = "p3" name = "p[]">
<select id = "pn3" name = "pn[]" data-target = "p3">
<option value = "0"></option>
<option value = "1">+</option>
<option value = "2">-</option>
</select>
<br /><br />
Total +:<br />
<input type = "text" id = "positive" name = "positive">
<br />
Total -:<br />
<input type = "text" id = "negative" name = "negative">
<br />Вот вам ответ с vanilla JS. Я прокомментировал JS-код, чтобы вы могли видеть, что я делал на каждом этапе. Я также изменил ваш HTML, сделав вводы с типом «число» вместо «текст». Таким образом, пользователь не сможет случайно ввести буквы в поле. Это немного упрощает проверку ошибок в дальнейшем. Я также изменил место, где отображаются итоги, чтобы они были абзацами, а не текстовыми полями, чтобы пользователь не мог ничего вводить туда. Как правило, я не люблю использовать ввод, если пользователь не должен вводить что-то там.
//declare shortcuts
const inputs = document.getElementsByTagName("input");
const selects = document.getElementsByTagName("select");
const ipr = "p";
const spr = "pn";
//loop through and add event listeners to all text boxes and dropdowns
for (var i = 0; i < inputs.length; i++) {
inputs[i].addEventListener("input", Compute)
}
for (var i = 0; i < selects.length; i++) {
selects[i].addEventListener("change", Compute)
}
function Compute() {
//set total positive and negative to zero
let pos = 0;
let neg = 0;
//loop through each text box-dropdown combo
for (var i = 1; i < 4; i++) {
//determine if sign is positive or negative and add or subtract accordingly
switch (document.getElementById(spr + i).value) {
case "1":
pos = pos + Number(document.getElementById(ipr + i).value);
break;
case "2":
neg = neg - Number(document.getElementById(ipr + i).value);
break;
default:
break;
}
}
//display each total on the page
document.getElementById("positive").innerHTML = pos;
document.getElementById("negative").innerHTML = neg;
}Price 1:<br />
<input type = "number" id = "p1" name = "p[]">
<select id = "pn1" name = "pn[]">
<option value = "0"></option>
<option value = "1">+</option>
<option value = "2">-</option>
</select>
<br />
Price 2:<br />
<input type = "number" id = "p2" name = "p[]">
<select id = "pn2" name = "pn[]">
<option value = "0"></option>
<option value = "1">+</option>
<option value = "2">-</option>
</select>
<br />
Price 3:<br />
<input type = "number" id = "p3" name = "p[]">
<select id = "pn3" name = "pn[]">
<option value = "0"></option>
<option value = "1">+</option>
<option value = "2">-</option>
</select>
<br /><br />
Total +:<br />
<p id = "positive">0</p>
Total -:<br />
<p id = "negative">0</p>