0

以下のコードを使用して、フォームのテキスト ボックスが空であるかどうかを確認しています。

function myFunction(){
    var week_no=document.getElementById("week_no").value;
    var date_rep=document.getElementById("date_rep").value;


    if(week_no==null || week_no=="")
    {
    alert("week_no field must be filled out");
    document.getElementById("week_no").style.background="pink";
    document.getElementById("week_no").focus();
    return false ;
    }
    if(date_rep==null || date_rep=="")
     {
    alert("date_rep field must be filled out");
    document.getElementById("date_rep").style.background="pink";
    document.getElementById("date_rep").focus();

    return false;
    }
}

次のように、HTML からこの JavaScript 関数を呼び出します。

<form id="form1" name="form1" method="post" onsubmit="return myFunction()" action="insert_alert.php" >    

私のフォームは非常に長いので、変数を作成して個々のフィールドにチェックを適用することができません。誰かが私の労力を減らすために私を導いてくれれば幸いです。

4

2 に答える 2

0

次のようにすべての入力を繰り返すことができます。

var inputs =  document.getElementById("form1").getElementsByTagName("input");
for(var i=0;i<inputs.length;i++) {
    var inp = inputs[i];
    if(inp.value == null || inp.value == "") {
        inp.style.background="pink";
    }
}
于 2012-10-24T06:48:45.803 に答える
0

jquery アプローチの使用:

<script>
    function myFunction() {
        var errorString = "";
        $("#form1 input[type='text']").css("background-color", "");
        $("#form1 input[type='text']").each(function (index, element) {
            if (errorString == "") {
                if (!$(element).val()) {
                    errorString += $(element).attr("id") + " field must be filled out";
                    $(element).css("background-color", "pink");
                }
            }
        });
        if (errorString) {
            alert(errorString);
            return false;
        }
        return true;
    }

</script>


<form id="form1" name="form1" method="post" onsubmit="return myFunction()" action="insert_alert.php" >
    <input type="text" id="week_no" />
    <input type="text" id="date_rep" />
    <input type="submit" value="go" />
</form>
于 2012-10-24T07:03:52.267 に答える