views:

2057

answers:

2

I'm creating some checkbox elements on the fly with jQuery and appending them to a node like so

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'm encountering are two-fold (there are in IE only)

  • Checkboxes are added to the page, but their default checked state is unchecked, when I'm specifying 'true' for that value. (Testing with 'checked' for the value makes no difference)
  • When alert( cbox.value ); executes, the output is 'on', every time.

I think the core problem here is I need a better way to set the default checked state of the checkboxes, and to set their default "value" attribute. But I haven't yet found another way.

Note: all of this code works fine in Firefox and Chrome.

This is jQuery 1.3.1 testing with IE 7.0.5730.11

+6  A: 

Internet Explorer doesn't like to let you change the checked value of an input that is not a part of the DOM. Try setting the checked value AFTER the item has been appended and see if that works.

Adam Raney
This is correct. Just confirmed it with a few tests.
Paolo Bergantino
I've run into this problem countless times in IE. Glad that solved the problem.
Adam Raney
+1  A: 

I reused some of your code and had a similar problem as per

http://stackoverflow.com/questions/3218898/why-does-order-of-defining-attributes-for-a-dynamically-created-checkbox-in-jquer

I found the resolution was to simply move the attribute declaration

type:  'checkbox', 

to the beginning i.e:

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

This problem occured in all browsers for me so i dont think its an IE issue but rather a jquery "thing". For me it didnt matter when i set the value (before or after) append. The difference was in how soon/where i declared the type of the input.

rism
+1 good one, I had the same problem, that fixed it
user1111111