chelder chelder - 3 months ago 21
ASP.NET (C#) Question

Combining ASP:Repeater and JQuery

I have the next C# code (which works):

// Write data into the checkboxes
RepeaterVocabularyWords.DataSource = new[] { correctWord1, correctWord2, incorrectWord1, incorrectWord2 };
RepeaterVocabularyWords.DataBind();

// Get data from the checkboxes
protected void ButtonAccept_Click(object sender, EventArgs e)
{
foreach (RepeaterItem item in RepeaterVocabularyWords.Items)
{
if (item.ItemType == ListItemType.Item
|| item.ItemType == ListItemType.AlternatingItem)
{
CheckBox CheckBoxVocabularyWord = (CheckBox)item.FindControl("CheckBoxVocabularyWord");
if (CheckBoxVocabularyWord.Checked)
{
}
}
}


And the next ASP with JQuery code (which works):

$(document).ready(function () {
$("input[id$='ButtonAccept']").click(function (e) {
if ($('span.storeCheck input:checked').length != 2) {
alert("You have to choose only the 2 words that means the same!");
e.preventDefault();
}


Then, if I write the line "span class="storeCheck"..," the above repeater code works, but not the above c# code:

<asp:Repeater ID="RepeaterVocabularyWords" runat="server" OnItemCommand="Repeater1_ItemCommand">
<ItemTemplate>
<<span class="storeCheck"><input runat="server" type="checkbox" ID="CheckBoxVocabularyWord" title="<%# Container.DataItem %>" /></span>
</ItemTemplate>
</asp:Repeater>


On contrast, if I write "asp:CheckBox ID="..," the above c# code works, but not the jQuery stuff.

<asp:Repeater ID="RepeaterVocabularyWords" runat="server" OnItemCommand="Repeater1_ItemCommand">
<ItemTemplate>
<asp:CheckBox ID="CheckBoxVocabularyWord" runat="server" Text="<%# Container.DataItem %>" />
</ItemTemplate>
</asp:Repeater>


How could I make both work?

Answer

The approach of Ray I think would work, but it is what I did finally.

The Jquery code is as follow:

<script type="text/javascript">
    $(document).ready(function () {
        $("input[id$='ButtonAccept']").click(function (e) {
            if ($('span.storeCheck input:checked').length != 2) {
                alert("You have to choose only the 2 words that means the same!");
                e.preventDefault();
            }
        });
    });
</script>

And the Repeater is:

<asp:Repeater ID="RepeaterVocabularyWords" runat="server" OnItemCommand="RepeaterVocabularyWords_ItemCommand">
    <ItemTemplate>
        <span class="storeCheck">
            <asp:CheckBox ID="CheckBoxVocabularyWord" Font-Size="0px" runat="server" Text="<%# Container.DataItem %>"
                ClientIDMode="Static" CssClass="{labelOn: '<%# Container.DataItem %>', labelOff: '<%# Container.DataItem %>', easing: 'easeOutBounce', duration: 500}" />
        </span>
    </ItemTemplate>
</asp:Repeater>

I'm writing a game. I'll put the link here if I finally upload it somewhere :)