お世話になります。jQueryを使用して、複数のフォーム内のinputやselectボックスのバリデーション行いたいと思っています。
今回、「WEB制作の現場で使うjQueryデザイン入門」という書籍を参考にしてサンプルを以下の様に作成しました。
http://music.geocities.jp/kinokolovers1/test/
さて、ある一つのフォーム内のsubmitをクリックすると、そのフォーム以外のinput要素もバリデーションの対象になってしまいます。
複数のフォームのバリデーションを行う場合でも、submitをクリックしたフォームだけをバリデーションの対象としたいと思っているのですが、どのようなコードの記述をすれば可能になりますでしょうか?
個人的な要望ですが、各フォームに、「form1」や「form2」などのIDをつけて、フォームの指定を行う方法もあるとは思いますが、
今回はフォームの名前やIDを指定して処理するのではく、「submitをクリックした親のformだけを対象にして、バリデーションを行う」といった処理をしたく思います。
どうぞ、ご教授いただけますよう、よろしくお願い致します。
validate する対象を拾い出す jQuery 関数を呼び出すときに、第2引数に this (form になってる) を指定します。
以下、コメントで「★」をつけたところに、this を入れておけば良いんじゃないでしょうか。
$("form").submit(function(){ //エラーの初期化 $("p.error", this).remove(); // ★ $("dl dd", this).removeClass("error"); // ★ $("input[type='text'].validate,textarea.validate", this).each(function(){ // ★ //必須項目のチェック if($(this).hasClass("required")){ if($(this).val()==""){ $(this).parent().prepend("<p class='error'>必須項目です</p>"); } } //数値のチェック if($(this).hasClass("number")){ if(isNaN($(this).val())){ $(this).parent().prepend("<p class='error'>数値のみ入力可能です</p>"); } } //メールアドレスのチェック if($(this).hasClass("mail")){ if($(this).val() && !$(this).val().match(/.+@.+\..+/g)){ $(this).parent().prepend("<p class='error'>メールアドレスの形式が異なります</p>"); } } //メールアドレス確認のチェック if($(this).hasClass("mail_check")){ if($(this).val() && $(this).val()!=$("input[name="+$(this).attr("name").replace(/^(.+)_check$/, "$1")+"]").val()){ $(this).parent().prepend("<p class='error'>メールアドレスと内容が異なります</p>"); } } }); //ラジオボタンのチェック $("input[type='radio'].validate.required", this).each(function(){ // ★ if($("input[name="+$(this).attr("name")+"]:checked").length == 0){ $(this).parent().prepend("<p class='error'>選択してください</p>"); } }); //チェックボックスのチェック $(".checkboxRequired", this).each(function(){ // ★ if($(":checked",this).length==0){ $(this).prepend("<p class='error'>選択してください</p>"); } }); // その他項目のチェック $(".validate.add_text", this).each(function(){ // ★ if($(this).prop("checked") && $("input[name="+$(this).attr("name").replace(/^(.+)$/, "$1_text")+"]").val()==""){ $(this).parent().prepend("<p class='error'>その他の項目を入力してください。</p>"); } }); //エラーの際の処理 if($("p.error").length > 0){ $('html,body').animate({ scrollTop: $("p.error:first").offset().top-40 }, 'slow'); $("p.error").parent().addClass("error"); return false; } });
ご回答ありがとうございました。
2016/09/20 10:17:57無事、期待したとおりの動作になりました!
このたびは本当にお世話になりました。
機会がございましたらまた、よろしくお願いいたします。