Làm bảng tính bằng javascript

TRUONG QUANG VU

Donkey Kong
Tham gia ngày
2/9/03
Bài viết
487
Reaction score
1
Mình viết 1 trang web html có kèm theo mã javascript để làm 1 máy tính giống casio mà ko hiểu sao nút cộng lại bị biến thành dấu để nối 2 số hạng lại với nhau chứ ko phải cộng 2 số hạng , ai biết chỉ giùm mình với !

PHP:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
   var x,y,kq;
   function checkX()
   {
      if(form1.sox.value.length==0)
   {
      alert("Hay nhap so thu nhat !");
   return false;
   }
   else
   {
       parseInt(x=form1.sox.value);
    return true;  
   }
   }
   
   function checkY()
   {
      if(form1.soy.value.length==0)
   {
      alert("Hay nhap so thu hai!");
   return false;
   }
   else
   {
      parseInt(y=form1.soy.value);
   return true;
   }
   }
   
   
   function cong()
   {
   kq=x+y;
   form1.ketqua.value=kq; 
   }
   
   function tru()
   {
      kq=x-y;
   form1.ketqua.value=kq;
   }
   
   function nhan()
   {
      kq=x*y;
   form1.ketqua.value=kq;
   }
   
   function chia()
   {
      kq=x/y;
   form1.ketqua.value=kq;
   }
</script>

</head>
<body>
<form id="form1" name="form1" method="post" action="">
  <p>
    <input name="sox" type="text" id="sox" size="10" onblur="checkX()" />
    <input name="con" type="button" id="con" value="+" onclick="cong()" />  
    <input name="tr" type="button" id="tr" value="-" onclick="tru()" />  
    <input name="nha" type="button" id="nha" value="*" onclick="nhan()" />  
    <input name="chi" type="button" id="chi" value="/" onclick="chia()" />  
    <input name="soy" type="text" id="soy" onblur="checkY()" size="10" />
  </p>
  <p>Kết quả = 
    <input name="ketqua" type="text" id="ketqua" size="40" />
</p>
</form>
</body>
</html>
 
Là vì thẻ input của form sẽ nhận giá trị là String, khi dùng toán tử "+" Browser chèn javascript hiểu là "cộng" 2 String, trong khi ở đây bạn muốn "cộng" 2 số, để cộng làm được theo ý bạn, trước tiên phải chuyển giá trị nhập vào ở sox va soy thành kiểu số.
Bạn dùng hàm parseInt là đúng rồi đấy, tuy nhiên trong phần else có thể viết là:
return parseInt(form1.soy.value);​

Hoặc có thể thử một biến trung gian như sau:
var x= parseInt(form1.sox.value);
var y= parseInt(form1.soy.value);
 
Back
Top