Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IE 7 does not like jquery('<button/>').attr('type','button')

I am trying to create a button using jquery. I use the following code

jquery('<button/>', {type:'button'}).text(name)

However this works in Safari , FF IE8 but not IE7

i tried to use the attr function :

jquery('<button/>').attr('type','button').text(name)

this does not work either.

any ideas what would work? I suppose if I don't assign a type it would default to button but i rather do that

thanks for your help

like image 870
salmane Avatar asked May 09 '10 19:05

salmane


2 Answers

Try this:

var button = $('<button type="button"/>');

Now, as it happens, the default type for buttons is "button" anyway in IE (7 at least, not sure about standards-mode 8). However the above should work. I just ran into this the other day. IE lets you provide the type right there in the element syntax when creating elements, and it seems that jQuery is pretty much passing its argument straight through to the low-level DOM API here.

Oh, and it works fine in FF and Chrome too.


edit — well what a difference a year makes, eh? I cannot get that mechanism to work for me at all now with jQuery 1.4.4 or jQuery 1.5.x. The good news is that jQuery 1.6 appears to work the way the OP wanted: via setting "type" in a more normal jQuery-like way.

What does seem to work, however, is to directly call ".setAttribute()" on the element. Thus:

var b = $('<button/>');
b[0].setAttribute('type', 'button');

does not throw an exception, and it does set the "type" attribute properly. (That's itself a little bizarre, as Microsoft clearly documents "type" as being read-only.) The change in 1.6 seems to be along the same lines. Formerly, the library did check "type" and would explicitly disallow its being set on elements already in the DOM, but would proceed to try and set it as a simple attribute for an element not in the DOM. Now, the 1.6 code calls ".setAttribute()" to set "type", which (for reasons unknown to me) works fine.

like image 174
Pointy Avatar answered Sep 19 '22 02:09

Pointy


Have you tried:

var $btn = $("<button>Button Text</button>");

Then you can append this anywhere in your document. Generally, you can create just about any DOM element using a string literal in this manner.

like image 25
BradBrening Avatar answered Sep 22 '22 02:09

BradBrening