$(document).ready(function(){
$('td:even').css('background-color', 'limegreen');
$('td:odd').css('background-color', 'blue');
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function() {
$(this).change(function(){
calculateSum();
checkduplicate();
});
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".txt").each(function() {
//add only if the value is number
if (!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
}
function checkduplicate(){
var sum = 0;
var arr = [];
var all = document.querySelectorAll('input[type=txt]');
all.forEach(function(el){
arr.push(el.value);
sum += +el.value;
console.info(arr);
console.info(sum);
var c = arr.filter(i =>i==el.value).length;
if (c>1){
var dupe = [...all].filter(e => e.value==el.value);
dupe.forEach(function(d){
if (d.value.trim() != ''){
d.style.border = '5px solid red';
d.style.color = 'red';
document.body.style.backgroundColor = "red";
}
});
}
});
}
$(document).ready(function(){
$('#btnClear').click(function(){
if (confirm("Want to clear?")){
/*Clear all input type = "text" box*/
$('#sumtable input[type = "txt"]').val(" ");
/*Reset sum to zero*/
$("span").html("0");
document.body.style.backgroundColor = "white";
location.reload();
$('td:even').css('background-color', 'limegreen');
$('td:odd').css('background-color', 'blue');
$(document).ready(function(){
$('td:even').css('background-color', 'limegreen');
$('td:odd').css('background-color', 'blue');
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function() {
$(this).change(function(){
calculateSum();
checkduplicate();
location.reload();
$('td:even').css('background-color', 'limegreen');
$('td:odd').css('background-color', 'blue');
/*Clear all input type = "text" box*/
$('#sumtable input[type = "txt"]').val(" ");
/*Reset sum to zero*/
$("span").html("0");
document.body.style.backgroundColor = "white";
});
});
});
}
});
});body {
font-family: sans-serif;
}
#summation {
font-size: 18px;
font-weight: bold;
color:#174C68;
}
.txt {
background-color: #FEFFB0;
font-weight: bold;
text-align: right;
}<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<meta charset = "utf-8"/>
<head>
<!--<script src = "jquery-3.3.1.min.js"></script>-->
<script src = "/home/cybrosys/Sethu/JS/jquery-3.3.1.min.js"></script>
<script src = "sumbox.js"></script>
<link rel = "stylesheet" href = "sumbox.css" type = "txt/css">
</head>
<body>
<table border = "2" align = "center" id = "sumtable">
<tbody>
<tr>
<td><input type = "txt" class = "txt" name = "txt" id = "qty1" class = "form-control alldifferent"></td>
<td><input type = "txt" class = "txt" name = "txt" id = "qty2" class = "form-control alldifferent"></td>
<td><input type = "txt"class = "txt" name = "txt" id = "qty3" class = "form-control alldifferent" ></td>
</tr>
<tr>
<td><input type = "txt" class = "txt" name = "txt" id = "qty4" class = "form-control alldifferent" ></td>
<td><input type = "txt" class = "txt" name = "txt" id = "qty5" class = "form-control alldifferent"></td>
<td><input type = "txt" class = "txt" name = "txt" id = "qty6" class = "form-control alldifferent" ></td>
</tr>
<tr>
<td><input type = "txt" class = "txt" name = "txt" id = "qty7" class = "form-control alldifferent" ></td>
<td><input type = "txt"class = "txt" name = "txt" id = "qty8" class = "form-control alldifferent"></td>
<td><input type = "txt" class = "txt" name = "txt" id = "qty9" class = "form-control alldifferent"></td>
</tr>
</tbody>
</table>
<div align = "center" >
<tr id = "summation"><br>
<td align = "center">Sum :</td>
<td align = "center"><span id = "sum">0</span></td></tr>
</div>
<td> </td>
<div align = "center">
<tr><td><button type = "button" id = "btnClear" value = "reset"/>Reset</td></tr>
</div>
</tr>
</body>
</html>Я не могу удалить повторяющиеся записи из полей ввода и автофокус в этих полях ввода. Также, когда я нажимаю кнопку сброса, генерируется сумма Nan.
У меня есть 9 полей ввода, где пользователь может вводить значения. После ввода значений генерируется сумма. Когда пользователь вводит повторяющиеся значения, эти записи выделяются красным цветом, и фон также становится красным.
Я пытаюсь удалить повторяющиеся записи и автофокус в этих полях. После сброса суммы до нуля и полей ввода до нуля. При повторном вводе значений сгенерированная сумма равна NaN. Как решить эти две проблемы?
Я не думаю, что вы можете сфокусировать несколько полей одновременно
при нажатии кнопки сброса значение суммы и поля ввода обнуляются. Затем при изменении ключа должна быть сгенерирована сумма значений.
<button type = "reset" id = "btnClear" value = "reset"/>Reset</td></tr> измените тип на "reset", это сбросит значение
@ chiliNut.... не нужно сосредотачиваться на нескольких полях одновременно. при изменении ключа мы вводим значения в поля ввода, при этом, если обнаруживаются повторяющиеся значения, они должны быть удалены и автоматически фокусироваться на соответствующем поле.
@tom ... да, это сбрасывает значение. но после нажатия кнопки сброса и ввода значений в поля сгенерированная сумма равна NaN. значение суммы должно быть сгенерировано при вводе значений в поля ввода.
это три ряда зафиксированы? или динамически изменены
Извини, что не понял тебя, Том. Строки фиксированы, значения внутри полей не фиксированы
в таблице у вас 3 строки исправлено? или добавление дополнительных строк
Исправлены 3 строки, не добавляя их
все значения во всех столбцах должны быть взяты для выполнения суммы. Сумма генерируется внизу таблицы.
K подожди .. есть какая-нибудь рабочий пример
@том нет у меня их нет
Попробуйте прослушиватель действий, чтобы вычислить сумму для всего текста
Давайте продолжить обсуждение в чате.
Он уже вычисляет сумму, используя событие изменения. Но после нажатия кнопки сброса сумма, сгенерированная при вводе значений, равна nan



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


При суммировании нужно изменить цвет и добавить d.focus();. Попробуй это:
$(document).ready(function(){
$('td:even').css('background-color', 'limegreen');
$('td:odd').css('background-color', 'blue');
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function() {
$(this).change(function(){
calculateSum();
checkduplicate();
});
});
});
var sum = 0;
function calculateSum() {
sum = 0;
//iterate through each textboxes and add the values
$(".txt").each(function() {
//add only if the value is number
if (!isNaN(this.value) && this.value.length!=0) {
sum += parseFloat(this.value);
this.style.color ='limegreen';
$('td:even').css('background-color', 'limegreen');
$('td:odd').css('background-color', 'blue');
this.style.border = 'limegreen';
}
});
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#sum").html(sum.toFixed(2));
}
function checkduplicate(){
var check=0;
var arr = [];
var all = document.querySelectorAll('input[type=txt]');
all.forEach(function(el){
arr.push(el.value);
sum += +el.value;
// console.info(arr);
//console.info(sum);
var c = arr.filter(i =>i==el.value).length;
if (c>1){
var dupe = [...all].filter(e => e.value==el.value);
check=0;
dupe.forEach(function(d){
if (d.value.trim() != ''){
if (check==0){
check=1;
}else{
d.style.border = '5px solid red';
d.style.color = 'red';
d.value = "";
d.focus();}
document.body.style.backgroundColor = "red";
}
else{
d.style.color ='limegreen';
$('td:even').css('background-color', 'limegreen');
$('td:odd').css('background-color', 'blue');
document.body.style.backgroundColor = "white";
}
});
}
});
}
$(document).ready(function(){
$('#btnClear').click(function(){
if (confirm("Want to clear?")){
/*Clear all input type = "text" box*/
$('#sumtable input[type = "txt"]').val(" ");
/*Reset sum to zero*/
$("span").html("0");
document.body.style.backgroundColor = "white";
setTimeout(function(){
window.location.reload(true);
});
$('td:even').css('background-color', 'limegreen');
$('td:odd').css('background-color', 'blue');
$(document).ready(function(){
$('td:even').css('background-color', 'limegreen');
$('td:odd').css('background-color', 'blue');
//iterate through each textboxes and add keyup
//handler to trigger sum event
$(".txt").each(function() {
$(this).change(function(){
calculateSum();
checkduplicate();
setTimeout(function(){
window.location.reload(true);
});
$('td:even').css('background-color', 'limegreen');
$('td:odd').css('background-color', 'blue');
/*Clear all input type = "text" box*/
$('#sumtable input[type = "txt"]').val(" ");
/*Reset sum to zero*/
$("span").html("0");
document.body.style.backgroundColor = "white";
});
});
});
}
});
});body {
font-family: sans-serif;
}
#summation {
font-size: 18px;
font-weight: bold;
color:#174C68;
}
.txt {
background-color: #FEFFB0;
font-weight: bold;
text-align: right;
}<script src = "https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<meta charset = "utf-8"/>
<head>
<!--<script src = "jquery-3.3.1.min.js"></script>-->
<script src = "/home/cybrosys/Sethu/JS/jquery-3.3.1.min.js"></script>
<script src = "sumbox.js"></script>
<link rel = "stylesheet" href = "sumbox.css" type = "txt/css">
</head>
<body>
<table border = "2" align = "center" id = "sumtable">
<tbody>
<tr>
<td><input type = "txt" class = "txt" name = "txt" id = "qty1" class = "form-control alldifferent"></td>
<td><input type = "txt" class = "txt" name = "txt" id = "qty2" class = "form-control alldifferent"></td>
<td><input type = "txt"class = "txt" name = "txt" id = "qty3" class = "form-control alldifferent" ></td>
</tr>
<tr>
<td><input type = "txt" class = "txt" name = "txt" id = "qty4" class = "form-control alldifferent" ></td>
<td><input type = "txt" class = "txt" name = "txt" id = "qty5" class = "form-control alldifferent"></td>
<td><input type = "txt" class = "txt" name = "txt" id = "qty6" class = "form-control alldifferent" ></td>
</tr>
<tr>
<td><input type = "txt" class = "txt" name = "txt" id = "qty7" class = "form-control alldifferent" ></td>
<td><input type = "txt"class = "txt" name = "txt" id = "qty8" class = "form-control alldifferent"></td>
<td><input type = "txt" class = "txt" name = "txt" id = "qty9" class = "form-control alldifferent"></td>
</tr>
</tbody>
</table>
<div align = "center" >
<tr id = "summation"><br>
<td align = "center">Sum :</td>
<td align = "center"><span id = "sum">0</span></td></tr>
</div>
<td> </td>
<div align = "center">
<tr><td><button type = "button" id = "btnClear" value = "reset"/>Reset</td></tr>
</div>
</tr>
</body>
</html>Для FireFox используйте location.reload(true);
привет @i_th, сумма после сброса полей ввода равна NaN. и я не могу удалить повторяющиеся записи и автоматически сфокусироваться на них
@Sethu, как это может быть. Я пробовал, и это работает, или я не понял вашу точку зрения. попробуйте использовать другой браузер.
я использую мозиллу фаерфокс. Я запустил отредактированный фрагмент и попытался решить ту же проблему.
@Sethu попробуйте использовать Chrome, и если он не работает, укажите свою проблему.
но независимо от браузера он должен работать правильно?
как удалить повторяющиеся записи из полей ввода?
Я попытался указать d.value='' , но он очищает предыдущее значение при обнаружении повторяющихся записей одного и того же.
@i_th... как удалить повторяющиеся записи из полей ввода
@Sethu, проверь это сейчас.
@Sethu попробуйте сейчас, он удаляет только дубликаты, потому что вы не ставите check ==0
sry i_th за ответ ... все правильно в браузере chrome, но не работает в mozilla
@Sethu Для FireFox используйте location.reload(true); вместо location.reload();, это работает.
@Sethu Я не знаю, что ты имеешь в виду.
вы должны генерировать сумму значений, когда вы нажимаете кнопку сброса, это правильно или нет?