JWorld@TW the best professional Java site in Taiwan
      註冊 | 登入 | 全文檢索 | 排行榜  

» JWorld@TW » Java SE 討論區  

按列印兼容模式列印這個話題 列印話題    把這個話題寄給朋友 寄給朋友   
reply to topicthreaded modego to previous topicgo to next topic
本主題所含的標籤
無標籤
作者 JS不可輸入小數點
eric9991517





發文: 7
積分: 0
於 2018-08-30 15:11 user profilesend a private message to userreply to postreply to postsearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
請問我該怎麼改成偵測到USER有輸入小數點符號就報錯誤訊息

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<!DOCTYPE html>
<html>
<body>
 
<td class=money ><input type="text" name="money" value="" style="width:60pt" onkeyup="return ValidateNumber(this,value)" />
<p id="show"></p>
 
<script>
 
 function ValidateNumber(e, pnumber)  {
      if (!/^\d+[.]?[0-9]{0,2}?$/.test(pnumber))      {
          var newValue = /\d+[.]?[0-9]{2}?/.exec(e.value);         
          if (newValue != null)  {             
              e.value = newValue;
              var x = String(newValue).indexOf('.');
        var y = String(newValue).length - x; 
 
              if(y > 1){
                document.getElementById("show").innerHTML = '超過小數點兩位數了';  
              }
          }   else {          
              e.value = "";
          } 
      }else{
      
      return false;
      }
  }
</script>
 
</body>
</html>


reply to postreply to post
作者 Re:JS不可輸入小數點 [Re:eric9991517]
kentyeh





發文: 643
積分: 6
於 2018-08-31 01:56 user profilesend a private message to userreply to postreply to postsearch all posts byselect and copy to clipboard. 
ie only, sorry for netscape users:-)add this post to my favorite list
我覺得根本不需要檢查USER輸入了多少位小數,
只需要告訴USER輸入規則即可,以下參考
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html>
<html>
<head>
  <script type="text/javascript">
      function checkForm(form){
         var ele = form.elements['money'];
         if(!ele.value || !/^\d+(\.\d{1,2})?$/.test(ele.value)){
             return alert('請輸入合理數值(最多兩位小數)'),ele.focus(),false;
         }
         return true;
      }
  </script>
</head>
<body>
  <form action="/action_page.php" onsubmit="return checkForm(this)">
    <input name="money" type="number" step="0.01" placeholder="最多兩位小數" pattern="\d+(\.\d{1,2})?" title="請輸入合理數值(最多兩位小數)" required autofocus><br/>
    <input type="submit" value="送出">
  </form>
</body>
</html>

說明:在比較新的瀏覽器,根不會用寫onsubmit=checkForm來檢查輸入,仍寫出來的原因是為了那些較舊的瀏覽器


reply to postreply to post
» JWorld@TW »  Java SE 討論區

reply to topicthreaded modego to previous topicgo to next topic
  已讀文章
  新的文章
  被刪除的文章
Jump to the top of page

JWorld@TW 本站商標資訊

Powered by Powerful JuteForum® Version Jute 1.5.8