Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I set the 'size' attribute for the element <input> using an attribute object?

Tags:

jquery

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.

like image 497
eyered Avatar asked Oct 24 '13 20:10

eyered


2 Answers

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.

like image 71
j08691 Avatar answered Sep 17 '22 19:09

j08691


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

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

http://jsfiddle.net/g9Hct/

like image 30
Yuriy Galanter Avatar answered Sep 19 '22 19:09

Yuriy Galanter