Saya ingin menambahkan nilai dengan mengklik tombol nilai oleh masing-masing dan setiap dengan fungsi berikut

function sum() {
  var txtFirstNumberValue = document.getElementById('txt1').value;
  var txtSecondNumberValue = document.getElementById('txt2').value;
  var txtThirdNumberValue = document.getElementById('txt3').value;
  var txtFourthNumberValue = document.getElementById('txt4').value;
  var result = parseInt(txtFirstNumberValue) + parseInt(txtSecondNumberValue);
  var result = parseInt(txtFirstNumberValue) + parseInt(txtThirdNumberValue);
  var result = parseInt(txtFirstNumberValue) + parseInt(txtFourthNumberValue);
  if (!isNaN(result)) {
    document.getElementById('txt1').value = result;
  }
}
// Here I gave the other two events to add to the text field by the id names
<!-- here I gave the three Value buttons and on click function -->
<input type="text" id="txt1"  value="10" />
<input type="button" id="txt2" value="10" onClick="sum();" />
<input type="button" id="txt3" value="20" onClick="sum();" />
<input type="button" id="txt4" value="30" onClick="sum();" />
-2
Jyothibabu 10 Agustus 2017, 09:55

2 jawaban

Jawaban Terbaik

Anda bisa mendapatkan nilai tombol dengan meneruskan this.value ke fungsi onClick di mana this mewakili elemen itu sendiri.

function sum(value) {
  document.getElementById('txt1').value = Number(document.getElementById('txt1').value) + Number(value);
}
<input type="text" id="txt1"  value="10" />
<input type="button" id="txt2" value="10" onClick="sum(this.value);" />
<input type="button" id="txt3" value="20" onClick="sum(this.value);" />
<input type="button" id="txt4" value="30" onClick="sum(this.value);" />
2
Erazihel 10 Agustus 2017, 07:39

Javascript ini akan membantu Anda.

<script>
    function sum(e) {
        var result = parseInt(e.value) + parseInt(document.getElementById('txt1').value);
        if (!isNaN(result)) {
                document.getElementById('txt1').value = result;
            }
    }
</script>
0
Haq Nawaz 10 Agustus 2017, 07:05