lunacafu
lunacafu

Reputation: 366

check checkbox status in jquery UI modal dialog

I have modal jQuery UI dialog with a checkbox:

            $dialog = $('<div id="formContainer"></div>')
                        .html('<div>some text</div><input id="accept_cb" type="checkbox" checked="checked"/> Uncheck this box to disable.<br />')
                        .dialog({
                                autoOpen: false,
                                title: 'Title ',
                                modal: true,
                                buttons: {
                                    "Close": function() {
                                        checkboxHandler();
                                    },
                                    Cancel: function() {
                                        $( this ).dialog( "close" );
                                    }
                                }
                            });


            function checkboxHandler(){
                if ($('#accept_cb').is(':checked'))
                {
                  alert('checked');
                }else{
                  alert('not checked');
                }
            }

When I open the dialog the first time everything works just fine and alerts the correct checked status. But when I return a second time the status stays either 'checked' or 'not checked' whatever it was the first time. What do I need to change?

I also tried with ().attr and ().prop, same result.

Upvotes: 0

Views: 2380

Answers (3)

Viktor Br
Viktor Br

Reputation: 11

Simple solution. You need to use class for checkbox and use selector with :last, because ui modal dialog made duplicate of this element.

function checkboxHandler(){
   if ($('.accept_cb:last').is(':checked'))
   {
      alert('checked');
   }else{
      alert('not checked');
   }
}

Upvotes: 1

Sinetheta
Sinetheta

Reputation: 9429

Closing a dialogue does not destroy it. Although you don't mention how you are opening the dialogue, I imagine that you are just running this code again. If so you are creating duplicates of all these elements. When you have 2 elements with the same ID on a page, your browser will always return the first one, hence your "whatever it was the first time".

Either .remove() the dialogue in the "close" handler, or don't re-create the contents each time.

Upvotes: 1

Ron van der Heijden
Ron van der Heijden

Reputation: 15070

In your code i see a syntax error. Pay attention on your '. Also see jQuery API for more information about checkboxes http://api.jquery.com/checked-selector/

Upvotes: 1

Related Questions