7

I am a jQuery beginner and have come across one of the methods to create a new element on the page. I am able to create the element fine. However, one of the attributes (size) defaults to 20 even though I clearly state that it should be bigger. Is this a jQuery bug, or am I missing something? The other attributes in the attribute object (type, autofocus) work fine.

The code I am using is this:

$('<input>', {
  'type' : 'text',
  'size' : 50,
  'autofocus' : 'true'
});

I do not have any CSS file.

When I use the attr() method, I am able to set the size. But I want to know that I am not the only one who is unable to set the size attribute for the element using an attribute object. I am using jQuery 1.9.1.

Any answers will be appreciated.

eyered
  • 117
  • 1
  • 8

3 Answers3

2

Use the .prop() function:

$('<input>', {
  'type' : 'text',
  'autofocus' : 'true'
}).prop('size','50');

Or this syntax:

$('<input>', {
   'type': 'text',
    prop: {
        size: "50"
    },
   'autofocus': 'true'
})

jsFiddle example

Here's the old bug report when it was discovered and the explanation as to why they didn't re-enable the old functionality.

j08691
  • 204,283
  • 31
  • 260
  • 272
2

As a workaround you can use "Size" with capital S:

$('<input>', {
  'type' : 'text',
  'Size' : 50,
  'autofocus' : 'true'
});

http://jsfiddle.net/g9Hct/

Yuriy Galanter
  • 38,833
  • 15
  • 69
  • 136
  • I like the heck, +1 :-) – The Alpha Oct 24 '13 at 20:54
  • Yes it works and checked it first then `+1`ed you, `HTML` attributes are not case sensitive. – The Alpha Oct 24 '13 at 20:56
  • I'd think this works in jQuery because different casing is working around jQuery explicitly forbidding setting of "size" attribute (as far as jQuery is concerned it's just some custom attribute) and it works in HTML because case, as @RecoveringSince2003 pointed out, doesn't matter in HTML attribute. – Yuriy Galanter Oct 24 '13 at 21:02
0

Interesting. I don't know why this is happening and can only assume that this is a jQuery bug as you assume.

You're already aware of using attr() to set the size, but for reference you can call that straight after creating the element (prior to adding it to the page or affecting it in any other way):

$('<input>', {
  'type' : 'text',
  'autofocus' : 'true'
}).attr('size', 50);

Another approach would be to simply add the attributes within the selector:

$('<input type="text" autofocus="true" size="50">');

JSFiddle demo of both in action.

James Donnelly
  • 126,410
  • 34
  • 208
  • 218