JQuery create element with attribute differences

I discovered something, and I think a little about why one of the methods works and the other does not. It only looks like IE7, but since IE7, sigh, still needs some support in the applications I work with.

The way that works in IE7

var month = jQuery('<input/>'); month.attr('id', 'DOBmonth'); month.attr('title', 'Enter month'); month.attr('type', 'text'); month.attr('size', '1'); month.attr('maxlength', '2'); month.attr('class', 'numbersOnly'); month.attr('value', mm); 

This method does not work

 var month = jQuery('<input/>', { id: 'DOBmonth', title: 'Enter month', type: 'text', size: 1, maxlength: 2, class: 'numbersOnly', value: mm }); 

Does anyone have an idea why only one way works in IE7, but everything is fine in IE8 +, FF, Chrome and Safari.

+8
jquery
source share
2 answers

The answer can be found in the API for the jQuery() function.

Note. Internet Explorer will not allow you to create an input or button element and change its type; you must specify the type using <input type="checkbox" /> for example. A demonstration of this may be lower:

Unsupported in IE:

 $('<input />', { type: 'text', name: 'test' }).appendTo("body"); 

Workaround supported:

 $('<input type="text" />').attr({ name: 'test' }).appendTo("body"); 
+21
source share

according to jQuery :

Note. Internet Explorer will not allow you to create an input element or button and change its type; you must specify the type

this does not work:

 $('<input />', { type: 'text', name: 'test' }).appendTo("body"); 

but it does:

 $('<input type="text" />').attr({ name: 'test' }).appendTo("body"); 
+3
source share

All Articles