raihan004
1/11/2015 - 4:31 PM

js calculator // source http://jsbin.com/tenevo

js calculator // source http://jsbin.com/tenevo

var input = document.querySelector("input"),
    val = document.querySelectorAll("span"),
    i=0,
    len=val.length;

for(;i<len;i++){
  val[i].addEventListener("click",getInput,false);
}

function getInput(e){
//   console.log(typeof e.target.innerHTML);
  
  if(e.target.innerHTML === "="){
//    console.log(input.value);
    input.value = eval(input.value);
  }else if(e.target.innerHTML==="C"){
    input.value="";
  }else{
    input.value+=e.target.innerHTML;
  }
  
}
span{
  display: inline-block;
  width: 24px;
  height: 20px;
  border: 1px solid blue;
  text-align: center;
  padding: 5px;
  box-sizing: border-box;/* added later , not tested , deleted it if output not good*/
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JS Bin</title>
<style id="jsbin-css">
span{
  display: inline-block;
  width: 24px;
  height: 20px;
  border: 1px solid blue;
  text-align: center;
  padding: 5px;
}
</style>
</head>
<body>
  <h1>My Calculator</h1>
  <input type="text" value="">
  <p>
    <span>1</span>
    <span>2</span>
    <span>3</span>
    <span>+</span>
  </p>
  <p>
    <span>4</span>
    <span>5</span>
    <span>6</span>
    <span>-</span>
  </p>
  <p>
    <span>7</span>
    <span>8</span>
    <span>9</span>
    <span>*</span>
  </p>
  <p>
    <span>C</span>
    <span>0</span>
    <span>=</span>
    <span>/</span>
  </p>
<script id="jsbin-javascript">
var input = document.querySelector("input"),
    val = document.querySelectorAll("span"),
    i=0,
    len=val.length;

for(;i<len;i++){
  val[i].addEventListener("click",getInput,false);
}

function getInput(e){
//   console.log(typeof e.target.innerHTML);
  
  if(e.target.innerHTML === "="){
//    console.log(input.value);
    input.value = eval(input.value);
  }else if(e.target.innerHTML==="C"){
    input.value="";
  }else{
    input.value+=e.target.innerHTML;
  }
  
}
</script>


<script id="jsbin-source-css" type="text/css">span{
  display: inline-block;
  width: 24px;
  height: 20px;
  border: 1px solid blue;
  text-align: center;
  padding: 5px;
}</script>

<script id="jsbin-source-javascript" type="text/javascript">var input = document.querySelector("input"),
    val = document.querySelectorAll("span"),
    i=0,
    len=val.length;

for(;i<len;i++){
  val[i].addEventListener("click",getInput,false);
}

function getInput(e){
//   console.log(typeof e.target.innerHTML);
  
  if(e.target.innerHTML === "="){
//    console.log(input.value);
    input.value = eval(input.value);
  }else if(e.target.innerHTML==="C"){
    input.value="";
  }else{
    input.value+=e.target.innerHTML;
  }
  
}</script></body>
</html>