2014年4月22日 星期二

javascript驗證資料後送出表單資料

之前我在寫一個HTML表單
發現如果表單內的按鈕寫送出
要經過javascript驗證資料
不管條件成不成立表單依然送出
範例如下
<form method="post" action="action.php" name="from1">
    帳號:
    <input name="id">
    密碼:
    <input name="password" type="password">
    <input name="send" type="submit">
</form>

顯示
當我帳號密碼都輸入進去按下送出
他就會以post方式送出去
但不管我裡面是否有資料都會送出
就算寫了javascript if判斷是否為空值也無法阻止送出
之後我查了許多資料發現要用點擊事件判斷加送出資料
不能使用type="submit"讓按鈕本身有送出資料的功能
這樣javascript就會是寫心酸的

所以表單送出按鈕改寫成普通的按鈕加上點擊事件(onclick)
<input name="send" value="送出" type="button" onclick="check()">

javascript部分
<script type="text/javascript">
    function check() {
        var id = document.getElementById("id");
        var pass = document.getElementById("password");
        if (id.value == "" || pass.value == "") {
            alert("請輸入完整資訊");
        } else {
            var from1 = document.getElementById("from1");
            from1.submit();
        }
    }
</script>

抓取from1的ID
如果條件成立就使用submit()送出資料
送出的目標就是from標籤action屬性那邊的連結
這樣子就可以按下按鈕後先做判斷資料是否完整
確定資料都有填入後才會送出資料
這問題困擾我很久所以就筆記一下

沒有留言:

張貼留言