Jonas T
Jonas T

Reputation: 3077

How to use the same name in input checkbox when we use asp:CheckBoxList

I usually avoid asp: controls and always use pure html controls with runat="server" due to their inflexibility. However, we have a system where it was built using those asp:controls. I have no choice but to follow the way it was built.

Here is the problem, when I data bind asp:CheckBoxList control DataTextField="Name" and DataValueField="ID", each input checkbox are using different names and when I need selected checkbox IDs, I have to loop through the whole checkboxlist to read the selected values.

If we use all those input name="Types" and read Request.Form["Types"] we can get all the selected ID values separated by commas, ",". In this way, I can avoid looping through all items in that checkboxlist. Is there any way we can do so that those input checkbox to use the same name?

Thanks.

EDIT:

I tried this and it is not working

ChkPropertyFeatures.Attributes.Add("name", "Types")

The reason I want to use the same name is not just to avoid loop at backend. I need to use jquery to select all those checkboxes by their name attribute. Yes, I know I can select by class name but I was wondering if I could change the name attribute of those checkboxes generated by Checkboxlist control.

Upvotes: 1

Views: 5482

Answers (2)

CoderRoller
CoderRoller

Reputation: 1259

A CheckBoxList generates a span wrapping each checkbox of the list:

<table id="CheckBoxList1">
    <tr>
        <td><span name="chenchi"><input id="CheckBoxList1_0" type="checkbox" name="CheckBoxList1$0" value="Uno" /><label for="CheckBoxList1_0">Uno</label></span></td>
    </tr><tr>
        <td><span name="chenchi"><input id="CheckBoxList1_1" type="checkbox" name="CheckBoxList1$1" checked="checked" value="Dos" /><label for="CheckBoxList1_1">Dos</label></span></td>
    </tr><tr>
        <td><span name="chenchi"><input id="CheckBoxList1_2" type="checkbox" name="CheckBoxList1$2" checked="checked" value="Tres" /><label for="CheckBoxList1_2">Tres</label></span></td>
    </tr>
</table>

You can change the name of each span dynamically this way:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not Page.IsPostBack Then
        For Each c As ListItem In Me.CheckBoxList1.Items
                   c.Attributes("name") = "chenchi"
        Next
    End If
End Sub

Then you can use jquery to find out if each checkbox is checked:

var sps = $('#CheckBoxList1').find('[name="chenchi"]');
sps.each(function (i) {
       alert( $(this).find('input:checkbox').attr('checked') ); 
});

Hope I understood your question well.

Upvotes: 0

Helen
Helen

Reputation: 33

You can not set the name of a web control from server side. If you need you can change the name attribute with javascript.

$("input[type='checkbox']").attr("name", "Types");

Upvotes: 1

Related Questions