with jQuery

by darkk6

HTML

<table>
    <tr>
        <td> 輸入學號:</td>
        <td> <input type="text" id="stuNO" /> </td>
        <td class="msg" id="stuNO_msg">  </td>
    </tr>
    <tr>
        <td> 輸入名字:</td>
        <td> <input type="text" id="name" /> </td>
        <td class="msg" id="name_msg">  </td>
    </tr>
    <tr>
        <td> 輸入班級:</td>
        <td> <input type="text" id="class" /> </td>
        <td class="msg" id="class_msg">  </td>
    </tr>
    <tr>
        <td colspan=2 style="text-align:center;">
            <input type="button" id="submit" value="送出" />
        </td>
        <td></td>
    </tr>
</table>

JavaScript

$(document).ready(function(){
    $("#submit").click(doCheck);
});

function doCheck(){
    var errorMsg="<font color=red>請填寫此欄位</font>";
    var isDone=true;
    
    //清掉之前的訊息
    $(".msg").html("");
    
    //檢查欄位是否填寫
    var tmpArr=new Array("stuNO","name","class");
    for(var key in tmpArr){
        if($("#"+tmpArr[key]).val().length==0){
            $("#"+tmpArr[key]+"_msg").html(errorMsg);
            isDone=false;
        }
    } 
    if(isDone){
        alert("所有欄位都填寫完成。");
    }
}