例如,我要寫一新增功能的php程式,程式確定可執行,但能在按按鈕送出資料庫前,先判斷所有欄位或單一位欄是否有填寫,均填寫後,按送出按鈕程式才會確定將欄位內的值或文字,送到資料庫。?
-------------------------------------------------------------------------------------------------------
請先將form標籤命名及設定送出事件為chk(),
如: <form action="" method="post" name="send" onsubmit="return chk();">
而表單內的需要填寫的欄位皆需命名,
而接下來再<script></script>內定義chk()的函式,
要得到表單內欄位的值的javascript寫法為:
document.表單名.欄位名.value
如果名為send的account的欄位為空值的javascript語法為:
if(document.send.account.value=='')
而警示視窗的語法為:
alert('警示文字');
如果要將焦點設定在名為send的account的欄位為空值的javascript語法為:
document.send.account.focus();
若某欄位為空值,
最後要傳回false阻擋表單送出,
若所有的欄位的填寫完畢後,
傳回true讓表單送出。
示範程式碼如下:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=big5">
<title>test</title>
<script type="text/javascript">
function chk(){
if(document.send.account.value==''){
alert('帳號未填');
document.send.account.focus();
return false;
}
if(document.send.pass.value==''){
alert('密碼未填');
document.send.pass.focus();
return false;
}
return true;
}
</script>
</head>
<body>
<form action="" method="post" name="send" onsubmit="return chk();">
帳號<input type="text" name="account" size="5" />
<br />
密碼<input type="password" name="pass" size="5" />
<br />
<input type="submit" value="送出" />
</form>
</body>
</html>
註:
因為JavaScript在Mozilla Firefox是可以被關閉的,
若使用者存心搗亂,
將選項的「使用javascript」的勾選取消,
您辛苦寫的JavaScript就完全無效了!
而您最好在php程式碼再將資料過濾一次,
如:
$account=$_POST['account'];
$pass=$_POST['pass'];
if(isset($account) && isset($pass)){
//在此處理$account與$pass
}else{
//輸出錯誤字串
}