12

Discovered something and am looking into a bit of incite as to why one way works and the other doesn't. Looks to be only an IE7 thing but as IE7, sigh, still needs some support in the apps I work in.

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 way doesn't work

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

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

3
  • 2
    Do you get Javascript errors using the second way in IE7? Commented Mar 27, 2012 at 22:11
  • IE7 and earlier have a write-once policy vis-a-vis type on input elements (once you set it, you can't change it). Guessing (hence not posting an answer), that for whatever reason, the first example is falling afoul that policy and the second isn't. Again, not an answer, but perhaps some insight. Commented Mar 27, 2012 at 22:17
  • also class should be in quotes for IE Commented Mar 21, 2013 at 9:43

2 Answers 2

29

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

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 can be seen below:

Unsupported in IE:

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

Supported workaround:

$('<input type="text" />').attr({
    name: 'test'
}).appendTo("body");
Sign up to request clarification or add additional context in comments.

Comments

5

according to jQuery:

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

this doesn't work:

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

but this does:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.