JQuery: getting the value/text/innerHtml of a checkbox in an ASP.NET CheckBoxList control

无人久伴 提交于 2019-12-12 09:05:31

问题


I've got a bunch of checkboxes generated by an asp.net CheckBoxList control. I want to get the text the user sees next to the control on the page.

With similar controls, like RadioButtonList, I've been able to get their values in jQuery by doing this:

var selected = $("input:checked[id*='" + Control.id + "']");

and then looping through and getting the value:

var whatIwant = selections[i].value;

(In this case, that "value" will be the text I want).

But - CheckBoxList renders differently. For each ListItem there's not only the input, but an html tag like so:

<input id="ctl00_ContentPlaceHolder1_ConsultedList_0" type="checkbox" name="ctl00$ContentPlaceHolder1$ConsultedList$0" />
<label for="ctl00_ContentPlaceHolder1_ConsultedList_0">Other service providers</label>

As you can see, the input tag itself, which is what my nice little jQuery query finds, doesn't include the info I want: "Other service providers". That's on the label tag.

Can anyone think of a good solution for this - maybe a good way of making the CheckBoxList render the text I need in the input tag, or some clever jQuery to find the labels that correspond to the selected inputs?


回答1:


You can use the selector you are already using (but just use the clientId), then get the next sibling (the label) and get its text value

e.g

$("#" + Control.ClientId).next().text();

Or you can just get the label by using its for attribute

$("label[for=" + Control.ClientId + "]").text();



回答2:


You will have to iterate over your form elements, searching for the label and grab its inner text, ASP .NET wraps the checkboxes inside a table with the ClientID of the control, you can use a selector like the following:

  var selection = [];
  $('#<%= CheckBoxList.ClientID %> :checked').each(function () {
    selection.push($(this).next('label').text());
  });

The HTML rendered by ASP .NET for CheckBoxLists looks like this:

<table id="check1" border="0">
    <tr>
        <td><input id="check1_0" type="checkbox" name="check1$0" />
                <label for="check1_0">Item 1</label></td>
    </tr><tr>
        <td><input id="check1_1" type="checkbox" name="check1$1" />
                <label for="check1_1">Item 2</label></td>
    </tr>
  .....
</table>

You can check an example with ASP .NET generated markup here.




回答3:


Lets see If ListItems have their text and values different ? -

I have explained all possible cases of getting values/text of checkbox or checkboxlist as below:-

Case-1:- If CheckBoxList Items Text and Values are same

<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>

call the below js function onclick or wherever you need (if required call in document.ready block)

function getChkVal1() {
            $chk_values = $("[id$=CheckBoxList1] input[type=checkbox]:checked").map(function (index, foElem) {
                return $(this).next().html();
            }).get();

            alert($chk_values);
        }

Case-2:- If CheckBoxList Items Values is in Numeric Order (e.g. 1,2,3 ...n Ofcourse, many times we use this way)

<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 would be as below

function getChkVal2() {
            $chk_values = $("[id$=CheckBoxList2] input[type=checkbox]").map(function (index, foElem) {
                if ($(this).is(":checked"))
                    return (index + 1);
            }).get();

            alert($chk_values);
        }

Case-3:- If CheckBoxList Items Values are some shortforms/initials of its text (e.g for Mango I would say "M")

Over here, I have used a trick to get the values of checkbox on page so that it can be easily accessible while writing js script. That is, I am using a hiddenfield with checkboxlist which will get all available values in checkboxlist during html parsing and store them on page in its value. See at below:-

<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) ) %>' />

I am using a html hiddenfield not the runat=server one as we dont need to write any code in cs using this hiddenfield. Here role of hiddenfield is nothing but the helper, which will provide comfort while writing js and to get the values of checkbox.

And now, let see the how the script would be look:-

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);
        }

Similarly you can do on radibuttonlist/radiobutton.




回答4:


Try using Control.ClientID

source [MSDN]

For example

 var selected = $("input:checked[id*='" + control.clientid + "']");

Please refer source for more options.



来源:https://stackoverflow.com/questions/1286317/jquery-getting-the-value-text-innerhtml-of-a-checkbox-in-an-asp-net-checkboxlis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!