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)
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
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.
I reused some of your code and had a similar problem as per
Why does order of defining attributes for a dynamically created checkbox in jquery affect its value?
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.
A checked checkbox's "checked" attribute does not have a state of true, it has a state of string "checked". I usually add elements to DOM with jQuery using:
var el = $('<input type="checkbox" id="topicFilter-' + '"'
+ ' checked="checked" />');
$(topicContainer).append(el);
More legible anyway, IMO, reads like HTML. I'll be damned if it doesn't work in IE, too, I've been doing it this way for years.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With