How To Calculate 2 Numbers Using Javascript

How To Calculate 2 Numbers Using Javascript, add and subtract multiply and divide two numbers with Javascript.

Bài tập làm phép toàn cộng, trừ, nhân, chia hai số bằng Javascript

How To Calculate 2 Numbers Using Javascript


1. Javascript


<script>
  function mycalc() {
    var x = Number(document.getElementById('txt1').value);
    var y = Number(document.getElementById('txt2').value);
    var op = document.getElementById('option').value;
    if (op === '+') {
      document.getElementById('result').innerHTML = x + y;
    }
    if (op === '-') {
      document.getElementById('result').innerHTML = x - y;
    }
    if (op === '/') {
      document.getElementById('result').innerHTML = x / y;
    }
    if (op === 'x') {
      document.getElementById('result').innerHTML = x * y;
    }
  }
</script>


2. HTML


<p>Number 1: <input type="text" id="txt1" /></p>
<p>Number 2: <input type="text" id="txt2" /></p>
<select id="option" style="width:50px">
  <option value="+">+</option>
  <option value="-">-</option>
  <option value="/">/</option>
  <option value="x">x</option>
</select>
<button onclick="mycalc();">=</button>
<span id='result'></span>

3. Demo


Number 1:

Number 2:

Nhận xét

×