2011-12-06 10 views
3

私はユーザーフォームを作成しています。これで私はテキストボックスと選択ドロップダウンの数がたくさんあります。 投稿後、私は$ _POSTでデータベースにすべての値を送っています。私のフォームは、このようなものです:選択ドロップダウン用の単一の検証スクリプト

 <tr> 
     <td>Review Employee Id</td> 
     <td><input type="text" name="rcode" id="rcode" class="genInputBox" /></td> 
    </tr> 
    <tr> 
     <td>Quality of Delivery</td> 
     <td> 
       <select name="qd" id="qd"> 
       <option value="">Plz Select Ratting </option> 
       <option value="5">5</option> 
       <option value="4">4</option> 
       <option value="3">3</option> 
       <option value="2">2</option> 
       <option value="1">1</option> 
       </select> 
     </td> 
     </tr> 

そして、より多くの選択ボックス.........

と、私はこの

var qd = document.product.qd.options[document.product.qd.selectedIndex].value; 
     if (qd == "") { 
      error_message = error_message + "Please select Rating In domain Knowledge\n"; 
      error = 1; 
     } 

のように使用していますセレクトボックスのvalidtionのために私は多くのことを述べましたフォーム内の選択ボックスの数。だから私の質問は、すべての選択ボックスに単一の選択ボックス検証スクリプトを使用できますか?

私は

var sels = document.product.getElementsByTagName("select"); 
for (var i=0,n=sels.length;i<n;i++) { 
    if (sels[i].selectedIndex<1) { 
    alert(sels[i].options[0]); // alerts Plz Select whatever 
    sels[i].focus(); 

    error_message = error_message + "Please select drop down\n"; 
    error = 1; } 
} 
    if (error == 1) { 
    alert(error_message); 
    return false; 
    } else { 
    return true; 
    } 

}

が、現在はチェックせずにダウン残された唯一の1つの選択ドロップ、選択ボックスのために、そのショー10エラーメッセージ場合は、この方法では、この答えを使用

。以下のような

+0

あなたはjQueryの検証のようなものを使用して考えがありますか? http://bassistance.de/jquery-plugins/jquery-plugin-validation/ – peterp

+2

いいえ、jqueryではなくjavascriptを使用します – ravinath

+0

次に、document.getElementsByTagName( 'select')を使用して、送信時にそれらを検証します。 – peterp

答えて

2

を役に立てば幸い

window.onload=function() { 
    var form = document.getElementsByTagName("form")[0]; // assuming first form on page 
    form.onsubmit=function() { 
    var sels = form.getElementsByTagName("select"); 
    for (var i=0,n=sels.length;i<n;i++) { 
     if (sels[i].selectedIndex<1) { 
     alert(sels[i].options[0]); // alerts Plz Select whatever 
     sels[i].focus(); 
     return false; // disallow submit 
     } 
    } 
    return true; // allow submission 
    } 
} 
+1

Dude。ナイスショット。とにかく、JQueryとは何ですか? haha :) フレームワークなしの小さなことをやろうとしていますが、あなたのような答えは、フレームワークapi *(jqueryの力から何も離れません)ではなく、言語そのものの美しさに感謝します。 PURE jsで実装しようとするオペレーションを見てください。 – stefgosselin

0

はいすることができます、: - 平野JS -

 
var firstSelectLen = document.product.qd.length; 
var secondSelectLen = document.product.qd1.length; // and so on for all selects you have 
//then loop with lengths to check if any selected 
//and show error msg accordingly 

が、それはこのように

+0

あなたはもっと記述してください......... – ravinath

関連する問題