Blog

Ponderings of a kind

This is my own personal blog, each article is an XML document and the code powering it is hand cranked in XQuery and XSLT. It is fairly simple and has evolved only as I have needed additional functionality. I plan to Open Source the code once it is a bit more mature, however if you would like a copy in the meantime drop me a line.

Atom Feed

jQuery XHTML Checkbox problems

Making it work

Whilst working on some jQuery (1.4.2) script in combination with the eXist-db bibliographic demo app, I had a situation whereby I was trying to switch XHTML form input checkboxes on and off when the user took certain actions.

I was using code similar to the following -

if(readPermissions.size() + writePermissions.size() >= 1) {
     $('#sharing-collection-with-other').attr('checked','checked');
} else {
     $('#sharing-collection-with-other').removeAttr('checked');
}

Which is very similar to what you will find on the web if you look for solutions to check and uncheck checkboxes with jQuery. Unfortunately this for me just would not work, whenever the user checked a check box I was completely unable to check it. Examining it with the debugger in Chrome I could see something like the following after removeAttr(...) is called - 

$('#sharing-collection-with-group'): Object
$('#sharing-collection-with-group').attr('checked'): undefined
$('#sharing-collection-with-group').is(':checked'): true

Now what drove me nuts is the last line from the debugger, was how can .is(':checked') return true when the attribute has been removed?

After an hour or so of Googling, trying different things and banging my head against the desk, I gave up and visited the jQuery IRC channel on FreeNode. After some explaining, trying a few suggestions and general disbelief, a very kind soul by the handle 'temp01' offered to take a look at my site and see what was going on.

'temp01' after confirming the problem soon noticed that I was using XHTML for my page content and not HTML. Apparently jQuery has some issues around XHTML and non-minimizable attributes such as 'checked'. There is a workaround however that he kindly provided me and I can confirm that it works well.

My fixed code now looks like this -

if(readPermissions.size() + writePermissions.size() >= 1) {
   $('#sharing-collection-with-other').get(0).checked = true;    
} else {
   $('#sharing-collection-with-other').get(0).checked = false;
}

Perfect! Thanks to the jQuery IRC community and especially to 'temp01' whomever you may be.

Adam Retter posted on Tuesday, 14th September 2010 at 13.04 (GMT+01:00)
Updated: Friday, 24th 2010 at September 05.56 (GMT-07:00)

tags: jQueryXHTMLcheckboxchecked

Comments (1)


temp01 is the Stig!

Add Comment



(will not be shown)






Tag Cloud