Creating checkbox elements on the go with jQuery - odd IE behavior

I create some checkbox elements on the fly using jQuery and add them to node this way

var topics = ['All','Cat1','Cat2'];
var topicContainer = $('ul#someElementId');

$.each( topics, function( iteration, item )
{
    topicContainer.append(
        $(document.createElement("li"))
        .append(
            $(document.createElement("input")).attr({
                 id:    'topicFilter-' + item
                ,name:  item
                ,value: item
                ,type:  'checkbox'
                ,checked:true
            })
            .click( function( event )
            {
                var cbox = $(this)[0];
                alert( cbox.value );
            } )
        )
        .append(
            $(document.createElement('label')).attr({
                'for':  'topicFilter' + '-' + item
            })
            .text( item )
        )
    )
} );

The problems I encounter are twofold (only available in IE)

  • Flags are added to the page, but their default state is not checked when I specify "true" for this value. (Testing with "checked" doesn't matter for the value)
  • When alert( cbox.value );executed, exit 'on' every time.

I think the main problem here is that I need a better way to set the default state of the checkboxes and set the “value” attribute to default. But I have not yet found another way.

Note. All this code works fine in Firefox and Chrome.

jQuery 1.3.1 IE 7.0.5730.11

+5
3

Internet Explorer , , DOM. , .

+14

jquery ?

,

type:  'checkbox', 

i.e:

$(document.createElement("input")).attr({
type:  'checkbox', 

, , IE, "" jquery. , ( ) append. , / .

+2

At the checked flag "checked" the attribute has no state true, it has the state of the string "checked". I usually add elements to the DOM using jQuery using:

var el = $('<input type="checkbox" id="topicFilter-' + '"'
         + ' checked="checked" />');
$(topicContainer).append(el);

More legible anyway, IMO reads as HTML. I will be damned if it does not work in IE either, I have been doing this for so many years.

+1
source

All Articles