자바스크립트 - 사칙 연산 계산기 만들기

반응형

더하기, 빼기, 곱셉, 나누기, 나머지 계산하는 계산기 입니다.

 

html

<h1>계산기</h1>
<div>
  <span>첫번째값: </span>
  <input type="numer" id="num1"/>
</div>
<div>
  <span>두번째값: </span>
  <input type="numer" id="num2"/>
</div>
<div>
  <button id="plusBtn">+</button>
  <button id="subBtn">-</button>
  <button id="multBtn">*</button>
  <button id="divBtn">/</button>
  <button id="restBtn">%</button>
</div>
<hr/>
<div>
  <span>계산결과: </span>
  <span id="result"></span>
</div>

 

javascript

const num1 = document.getElementById('num1');
const num2 = document.getElementById('num2');
const plusBtn = document.getElementById('plusBtn');
const subBtn = document.getElementById('subBtn');
const multBtn = document.getElementById('multBtn');
const divBtn = document.getElementById('divBtn');
const restBtn = document.getElementById('restBtn');

const result = document.getElementById('result');

console.log(num1.value);

plusBtn.addEventListener('click', () => {
  result.innerText = parseInt(num1.value) + parseInt(num2.value);;
})
subBtn.addEventListener('click', () => {
  result.innerText = parseInt(num1.value) - parseInt(num2.value);;
})
multBtn.addEventListener('click', () => {
  result.innerText = parseInt(num1.value) * parseInt(num2.value);;
})
divBtn.addEventListener('click', () => {
  result.innerText = parseInt(num1.value) / parseInt(num2.value);;
})
restBtn.addEventListener('click', () => {
  result.innerText = parseInt(num1.value) % parseInt(num2.value);;
})

 

CodePen 예시

 

See the Pen calc by powerku (@powerku) on CodePen.

 

728x90
반응형