2016-09-12 9 views
-2

error_spanで最も近いspanを見つけたいと思います。 jQueryを使ってどうすればいいですか?div内の特定のクラスを持つ最も近いスパンを見つける

<div class="form-group row"> 
    <div class="col-sm-4"> 
     <label for="reimburse_price" class="control label">Amount</label> 
    </div> 
    <div class="col-sm-8"> 
     <div> 
      <input type="text" name="reimburse_price" min="1" placeholder='0.00' class="form-control numberOnly" id="reimburse_price" required>   
     </div> 
     <div> 
      <span class="small text-danger error_span"></span>  
     </div> 
    </div> 
</div> 

私のjavascriptのは、私のjqueryの関数はここ

function checkNumInput(id){ 
    if ($(id).val() == "") { 
     $(id)[0].setCustomValidity('Please fill out this field'); 
     $(id).closest("span .error_span").text("Please fill out this field").removeClass("hidden").addClass("text-danger"); 
    } 
} 
+1

一番近い親ですか?どの要素に最も近いか? –

+0

? – Joseph

+0

どの要素に関連していますか? –

答えて

4

あなたの現在のコードの問題がclosest()は、親要素を見て、まだspanは、あなたがしたいということですされ、ここで

$("#reimburse_price").blur(function(){ 
    checkNumInput("#reimburse_price"); 
}); 

ですfindはinputへの親の兄弟の子です。

問題を解決するには、inputspanの両方の共通の親に移動し、そこからfind()を使用してください。試してみてください:

$("#reimburse_price").blur(function() { 
    checkNumInput('#' + this.id); 
}); 

function checkNumInput(id) { 
    var $input = $(id); 
    if ($input.val() == "") { 
     $input.get(0).setCustomValidity('Please fill out this field'); 
     $input.closest('.form-group').find('.error_span').text("Please fill out this field").toggleClass("hidden text-danger"); 
    } 
} 
+0

それはちょうどうまく働いたおかげで。最後の最後の質問の1つは、クラスform-groupを持つdiv内に他のスパンがある場合、私の関数が動作するでしょうか? – healer

+0

'.form-group'クラスを持つ複数の要素がある場合でも動作しますが、これらの要素の両方にテキストとクラスが設定されます –

+0

私の手続きはうまくいきますか?要素のIDを渡す私の関数では、最も近い.formグループクラスしか見つからないでしょうか? – healer

関連する問題