Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery create element with attribute differences

Tags:

jquery

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.

like image 473
Micah Montoya Avatar asked Mar 27 '12 22:03

Micah Montoya


People also ask

How to get attr value jQuery?

The attr() method sets or returns attributes and values of the selected elements. When this method is used to return the attribute value, it returns the value of the FIRST matched element. When this method is used to set attribute values, it sets one or more attribute/value pairs for the set of matched elements.

Have attr jQuery?

hasAttribute is a JavaScript native function and is applied directly to an HTML element. When we select an element with jQuery, a jQuery object is returned with a collection of elements that match the specified selector.

How set value to data attribute in jQuery?

The attr() method in jQuery is used to set or return the attributes and values of the selected elements.


1 Answers

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");
like image 71
Anthony Grist Avatar answered Nov 16 '22 00:11

Anthony Grist