2016-07-28 2 views
-1

jQueryが選択項目の数に応じてカウントを追加していますが、複数のセレクタと複数のカウント表示フィールドがあります。なぜこれがうまくいかないのかよく分かりません。jQuery .on()関数が意図したとおりに動作しない

私が1を変更すると、すべての選択のカウントが変更されます。ここで

/*Account Group Count*/ 
$('body').on('change', $('#group-accounts'),function() { 
    var strAccount = $("select option:selected").length; 
    $(".AccountCount").text(strAccount); 
    $(".AccountSmallCount").text(strAccount + ' selected'); 
}); 

/*User Group Count*/ 
$('body').on('change', $('#group-users'),function() { 
    var strUser = $("select option:selected").length; 
    $(".UsersCount").text(strUser); 
    $(".UsersSmallCount").text(strUser + ' selected'); 
}); 

が選択

<div class="ui-multiselect col-full group-accounts-select">     
     <select name="group-accounts" id="group-accounts" multiple> 
      <cfloop query="AccountGroupList"> 
       <option value="<cfoutput>#AccountGroupList.aprimID#</cfoutput>"><cfoutput>#aName#</cfoutput></option> 
      </cfloop>     
     </select> 
     <label for="group-accounts"><span>Accounts:</span></label> 
    </div> 
    <span class="AccountSmallCount"></span> 
+3

[MCVE] –

+3

は、なぜあなたが渡しているを提供してくださいセレクタの代わりにjQueryオブジェクト? –

+0

このような単純な基本的な間違いをする前に、APIを読んでください。 – vsync

答えて

2
/*Account Group Count*/ 
$(document).on('change', '#group-accounts', function(){ // <-- the difference 
    var strAccount = $(this).find(":selected").length; 
    $(".AccountCount").text(strAccount); 
    $(".AccountSmallCount").text(strAccount + ' selected'); 
}); 

/*User Group Count*/ 
$(document).on('change', '#group-users', function(){ // <-- the difference 
    var strUser = $(this).find(":selected").length; 
    $(".UsersCount").text(strUser); 
    $(".UsersSmallCount").text(strUser + ' selected'); 
}); 

の一つですこれは、あなたがそれ(委任)行う方法です。

//[root element] [event] [target selector] [callback] 
    $( document).on('change', '#group-users', function(){..} 
+1

ここでイベントを委任していません。これはOPのコードと同じ動作ではありません –

+0

私は変更します – vsync

+1

ありがとうございます@vsync – Charles

関連する問題