ListItems のテキストと値が異なるかどうか見てみましょう。-
以下のように、チェックボックスまたはチェックボックスリストの値/テキストを取得する可能性のあるすべてのケースを説明しました:-
ケース 1:- CheckBoxList 項目のテキストと値が同じ場合
<asp:CheckBoxList ID="CheckBoxList1" runat="server" Width="180">
<asp:ListItem Value="SQL" Text="">SQL</asp:ListItem>
<asp:ListItem Value="ASP.Net" Text="">ASP.Net</asp:ListItem>
<asp:ListItem Value="jQuery" Text="">jQuery</asp:ListItem>
<asp:ListItem Value="MVC" Text="">MVC</asp:ListItem>
<asp:ListItem Value="IIS" Text="">IIS</asp:ListItem>
</asp:CheckBoxList>
以下のjs関数をonclickまたは必要な場所で呼び出します(必要な場合はdocument.readyブロックで呼び出します)
function getChkVal1() {
$chk_values = $("[id$=CheckBoxList1] input[type=checkbox]:checked").map(function (index, foElem) {
return $(this).next().html();
}).get();
alert($chk_values);
}
ケース 2:- CheckBoxList 項目の値が数値順の場合 (例: 1,2,3 ...n もちろん、この方法を何度も使用します)
<asp:CheckBoxList ID="CheckBoxList2" runat="server" BackColor="#ffcccc" Width="180">
<asp:ListItem Value="1" Text="">SQL</asp:ListItem>
<asp:ListItem Value="2" Text="">ASP.Net</asp:ListItem>
<asp:ListItem Value="3" Text="">jQuery</asp:ListItem>
<asp:ListItem Value="4" Text="">MVC</asp:ListItem>
<asp:ListItem Value="5" Text="">IIS</asp:ListItem>
</asp:CheckBoxList>
js関数は以下のようになります
function getChkVal2() {
$chk_values = $("[id$=CheckBoxList2] input[type=checkbox]").map(function (index, foElem) {
if ($(this).is(":checked"))
return (index + 1);
}).get();
alert($chk_values);
}
ケース 3:- CheckBoxList アイテムの値がテキストの省略形/イニシャルである場合 (たとえば、Mango の場合は「M」とします)
ここでは、トリックを使用してページ上のチェックボックスの値を取得し、js スクリプトの作成中に簡単にアクセスできるようにしました。つまり、html 解析中にチェックボックス リストで使用可能なすべての値を取得し、その値でページに格納する、チェックボックス リストで hiddenfield を使用しています。以下を参照してください:-
<asp:CheckBoxList ID="CheckBoxList3" runat="server" BackColor="#ffccff" Width="180">
<asp:ListItem Value="S" Text="">SQL</asp:ListItem>
<asp:ListItem Value="A" Text="">ASP.Net</asp:ListItem>
<asp:ListItem Value="J" Text="">jQuery</asp:ListItem>
<asp:ListItem Value="M" Text="">MVC</asp:ListItem>
<asp:ListItem Value="I" Text="">IIS</asp:ListItem>
</asp:CheckBoxList>
<input type="hidden" id="hdnChkBox3" value='<%=String.Join( ",", CheckBoxList3.Items.Cast<ListItem>().Select(item=>item.Value) ) %>' />
この隠しフィールドを使用して cs にコードを記述する必要がないため、runat=server ではなく html 隠しフィールドを使用しています。ここでの hiddenfield の役割はヘルパーに他なりません。ヘルパーは、js の記述中に快適さを提供し、チェックボックスの値を取得します。
そして今、スクリプトがどのように見えるか見てみましょう:-
function getChkVal3() {
$chk_items = $("#hdnChkBox3").val().split(","); // Get all checkboclist values from hiddenfield and convert it to array using split()
// so now we have ItemIndex and Values Index in Array as parallel
$chk_values = $("[id$=CheckBoxList3] input[type=checkbox]").map(function (index, foElem) {
if ($(this).is(":checked")) {
return ($chk_items[index]);
}
}).get();
alert($chk_values);
}
同様に、radibuttonlist/radiobutton でも実行できます。