2

I have application in ASP.NET with CheckBoxList:

<asp:CheckBoxList runat="server" ID="myCheckBoxList">
    <asp:ListItem Text="1 16" />
    <asp:ListItem Text="1 17" />
    <asp:ListItem Text="2 20" />
</asp:CheckBoxList>

I want to change style for selected elements after button click. To do that I have JavaScript fuction:

function changeColor() {
    var checkBoxList = document.getElementById("myCheckBoxList");
    var options = checkBoxList.getElementsByTagName('input');

    for (var i = 0; i < options.length; i++) {
        console.log(options[i].checked);
        if (options[i].checked) {
            options[i].parentElement.className = 'Red';
        }
    }
}

When I click button, selected items change their colors for a very short moment (about 0,5 second) and then they back to default black color. Why my checkboxlist items style reset? I do not want this behaviour. How can I change my code to change color permamently (not just for 0,5 second)?

1
  • You changed the class name permanently, check you might have a postback or your checkboxlist items might have created again Commented Mar 21, 2016 at 11:26

1 Answer 1

1

Here is complete solution:

<script type="text/javascript">
    function changeColor() {
        var checkBoxList = $('[id$="myCheckBoxList"]');
        var options = checkBoxList[0].getElementsByTagName('input');

        for (var i = 0; i < options.length; i++) {
            console.log(options[i].checked);
            if (options[i].checked) {
                options[i].parentElement.className = 'Red';
            }
        }

        return false;
    }
</script>

<asp:CheckBoxList runat="server" ID="myCheckBoxList">
    <asp:ListItem Text="1 16" />
    <asp:ListItem Text="1 17" />
    <asp:ListItem Text="2 20" />
</asp:CheckBoxList>

<asp:Button OnClientClick="return changeColor();" Text="Test" runat="server" /> 

I've localized myCheckBoxList using jQuery, because it can have different Id in the browser if you are using master page. Secondly I return false from the function to prevent postback on button click in order to maintain class value.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. It works perfect. I probably do unintentionally postback. Of course there should be options[i].parentElement.style.color = 'Red' - my mistake

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.