-3

I have problems to change background color of dynamic created buttons.I have lots of button on the page created dynamically.I want to have in the first click to the button to change background color to green on the second click i want to take this change back.Wıth below code i tried to do it with %2 ==0 but than i realized it second click could be on other button and even it is the second click i want to make it green.I think i have to loop through every button than apply below code but i couldnt do it(This was my first question).Second question is finally i would like to send just green buttons value (text value) to a listbox.Below is my code but i am not succeed it.Can you please help

<asp:ListBox ID="ListBox2" runat="server" Width="111px"></asp:ListBox>


        $(function () {
            var count = 0;
            $('input[type=button]').on('click', function (e) {
                e.preventDefault();
                count += 1;
                if (count % 2 === 0) {
                    $(this).css('background-color', '#6FA478');
                    var value = $(this).value;
                    $("[id$=ListBox2]").append($('<option/>').text(value).attr('value', value));
                }
                else {
                    $(this).css('background-color', '');
                }
            });
        });     
4

2 回答 2

1

You should try this, It will make a button green and store in list if click on first time, if second click then it will remove from list box and remove the green background color also, and it will work continue in on and off mode.

$(function () {
    $('input[type=button]').on('click', function (e) {
        e.preventDefault();
        var toggle = $(this).data('toggle');
        var value = $(this).val();
        if(toggle && toggle == "1") {
            $(this).css('background-color', '');
            $('[id$=ListBox2] option[value="'+value+'"]').remove()
            $(this).data('toggle', '0');
        }else{
            $(this).css('background-color', '#6FA478');      
            $("[id$=ListBox2]").append('<option value="'+value+'">'+value+'</option>');
            $(this).data('toggle', '1');
        }
    });
});

or you can try .toggle also like

$(function () {
    $('input[type=button]').toggle(function (e) {
       e.preventDefault();
       var value = $(this).val();
       $(this).css('background-color', '#6FA478');      
       $("[id$=ListBox2]").append('<option value="'+value+'">'+value+'</option>');
    }, function(e){
       e.preventDefault();
       var value = $(this).val();
       $(this).css('background-color', '');
       $('[id$=ListBox2] option[value="'+value+'"]').remove()
   });
});
于 2012-11-01T12:50:50.257 回答
0
$(':button').toggleClass(["red", "green"])

in your css file, ensure that red and green have values

于 2012-11-01T12:28:57.943 回答