いつもお世話になっております。
jQueryでValidationの実装を試しているのですが、.closestが.form-groupを参照できていないせいか、Bootstrapの.has-errorを.form-groupにaddClass出来ない上に、HTML側にエラーメッセージが出力できません。
長らく試行錯誤しましたが、書き方が間違っているのか、その他に原因があるのかも分かりませんでした。
どなたかアドバイスをお願いします。
html
1<!DOCTYPE html> 2<html lang="ja"> 3<head> 4 <meta charset="UTF-8"> 5 <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous"> 6 <link rel="stylesheet" type="text/css" href="style.css"> 7 <title>Validation</title> 8</head> 9<body> 10<form> 11<div class="form-group"> 12 <label>名前 任意<span class="help-block"></span> 13 <input type="text" name="name" class="valid-text form-control"> 14 </label> 15</div> 16</form> 17</body> 18<script src="https://code.jquery.com/jquery-3.0.0.min.js" integrity="sha256-JmvOoLtYsmqlsWxa7mDSLMwa6dZ9rrIdtrrVYRnDRH0=" crossorigin="anonymous"></script> 19<script src="main.js"></script> 20</html>
main.js
1$(function(){ 2 const MSG_TEXT_MAX = '20字以内で入力してください。'; 3 4 $('.valid-text').keyup(function(){ 5 6 var form_g = $(this).closest('.form_group'); 7 if($(this).val().length > 20){ 8 console.log("over20"); 9 form_g.addClass('has-error'); 10 form_g.find('.help-block').text(MSG_TEXTAERA_MAX); 11 }else{ 12 console.log("under20"); 13 form_g.removeClass('has-error'); 14 form_g.find('.help-block').text(" "); 15 } 16 17 }); 18 19 20});

回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
退会済みユーザー
2016/06/16 08:08
2016/06/16 08:12
退会済みユーザー
2016/06/16 08:15
2016/06/16 08:17
2016/06/16 08:33
退会済みユーザー
2016/06/16 08:47