tara tara - 5 months ago 5
jQuery Question

Can't calculate automatically Javascript

HTML

<select id="k1" onchange="kes1();" name="kelayakan1" size="1">
<option value="">-- Pilih Salah Satu --</option>
<option value="1">Layak</option>
<option value="0">Tidak Layak</option>
</select>
<br>
<select id="k2" onchange="kes2();" name="kelayakan2" size="1">
<option value="">-- Pilih Salah Satu --</option>
<option value="1">Layak</option>
<option value="0">Tidak Layak</option>
</select>
<br>
<br>
<table style="width:30%;" border="1">
<thead>
<tr>
<th colspan="5">TES</th>
</tr>
<tr>
<th></th>
<th>A</th>
<th>B</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>
<div id="aa1" class="layak" style="text-align:center;"></div>
</td>
<td>
<div id="aa2" class="layak" style="text-align:center;"></div>
</td>
</tr>
<tr>
<td>2</td>
<td>
<div id="bb1" class="layak" style="text-align:center;"></div>
</td>
<td>
<div id="bb2" class="layak" style="text-align:center;"></div>
</td>
</tr>
<tr>
<td>Result</td>
<td>
<div id="hasil1" style="text-align:center;"></div>
</td>
<td>
<div id="hasil2" style="text-align:center;"></div>
</td>
</tr>
</tbody>
</table>


JS

function kes1() {
var ap = document.getElementById('k1').value;
var satu = 1;
var nol = 0;
if (ap == "1") {
document.getElementById('aa1').innerHTML = satu;
document.getElementById('aa2').innerHTML = nol;
} else {
document.getElementById('aa1').innerHTML = nol;
document.getElementById('aa2').innerHTML = satu;
}
}
function kes2() {
var bp = document.getElementById('k2').value;
var satu = 1;
var nol = 0;

if (bp == "1") {
document.getElementById('bb1').innerHTML = satu;
document.getElementById('bb2').innerHTML = nol;
} else {
document.getElementById('bb1').innerHTML = nol;
document.getElementById('bb2').innerHTML = satu;
}
}
$(document).ready(function() {
//Iterate through each Textbox and add keyup event handler
$(".layak").each(function() {
$(this).innerHTML(function() {
//Initialize total to 0
var total = 0;
$(".layak").each(function() {
// Sum only if the text entered is number and greater than 0
if (!isNaN(this.value) && this.value.length != 0) {
total += parseFloat(this.value);
}
});
//Assign the total to label
//.toFixed() method will roundoff the final sum to 2 decimal places
$("#hasil1").val(total);
});
});
});


I want to calculate A1 and A2, B1 and B2 and appear on result..

if 1+0=1, if 1+1=2, if 0+0=0

but still can't working well :(

This jsfiddle.. https://jsfiddle.net/taraym/57Ltreb0/

may you know how to solve it

Answer

I updated your question with a working version https://jsfiddle.net/57Ltreb0/8/.

See Is there any function like IsNumeric in javascript to validate numbers to understand the func isNumeric that I added

Let me know if it helps you.