網頁Web-Javascript-表單空值提示

  • 9716
  • 0
  • Web
  • 2023-07-11

1.html-空值提示

2.javascript-空值提示

3.實作:讓使用者輸入數量1-10

  • 3-1.空值提示:
    • 提示文字"輸入數量1-10"
  • 3-2.使用者輸入正確(1-10)時:
    • 提示文字"OK"
  • 3-3.使用者輸入不正確時:
    • 提示文字 "請輸入1-10"
  • 3-4.輸入其他字串時:
    • 提示文字"無效數值"
  • 3-5.數入大於10時
    • 提示文字"庫存量不足"

 


 

1.html-空值提示

在<input> 裡面 加上 "必填" required

page.html

<html>
<head></head>

<body>
<form> 
  Name:<input type="text" name="myname" required>  
  <input type="submit" value="送出">
</form>

</body>
</html>

 

2.javascript-空值提示

page.html

<html>
<head></head>

<body>

<form name="myForm" onsubmit="return validateForm()" method="get">

 Name: <input type="text" name="myname"> 
 <input type="submit" value="送出"> 

</form>
</body>

</html>

<script>
function validateForm() { 
var x = document.forms["myForm"]["myname"].value;
    if (x == "") {
         alert("不能為空值");      
         return false; 
    }
 } 
</script>

參考

https://codepen.io/yiruatstudio/pen/rNLKyMW

 

3.實作:讓使用者輸入數量1-10

page.html

<html>
<head>
</head>

<body> 
 
<p>請輸入你要購買的數量1-10:</p> 
 
<input type="text" id="numb"> 
 
<button type="button" onclick="myFunction()">送出</button> 
 
<p id="demo"></p>

</body>


</html>

<script>

function myFunction() { 
 
   x = document.getElementById("numb").value; 
   console.log(x);//可以用F12 console 看是否有抓到值

    if(x == ""){ 
        text = "請輸入數量1-10";   
    }else if (x < 1 || x > 10) {   
        text = "庫存量不足"; 
    }else if(x >=1 || x <= 10){ 
        text = "OK!";   
    }else{
	text = "無效數值";
    }  
	
   document.getElementById("demo").innerHTML = text; 
}

</script>

參考

https://codepen.io/yiruatstudio/pen/NWrzpYq

Yiru@Studio - 關於我 - 意如