views:

275

answers:

3

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

+1  A: 

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.

BradBrening
that would work no doubt my trouble is with the "type" of the button.as soon as i assign that IE 7 rejects it
salmane
You could certainly do this: var $btn = $("<button type='submit'>Button Text</button>");
BradBrening
I tried that too but it did not work. some how , as soon as i introduce the type attribute IE7 does not like....could this be a jquery 1.4 bug?
salmane
Interesting. I don't have IE7 to test this on. If it works in other browsers, I doubt the issue is with jQuery though.
BradBrening
+2  A: 

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.

Pointy
It must be something on my end cause i tried that and it still does not work. It seems to me that IE7 , IE8 , FF and Safari have type="button" as the default too...maybe I will just leave it undeclared
salmane
No, that's definitely not correct: all the "good" browsers follow the W3C spec, which stipulates that the default type is "submit". (Well that's in "standards mode"; if you're in quirks mode, well (A) I don't know what they do and (B) get out of quirks mode.)
Pointy
Also, that definitely works in IE. What do you mean, exactly, when you say "it still does not work"? Do you get a Javascript error?
Pointy
sorry guys, what i ment was that the browser throws back an error about jquery here it is : Message: Object doesn't support this property or methodLine: 20Char: 49Code: 0URI: http://www.example.com/js/jquery.jsit is odd because it points to the jquery file not my script.
salmane
That's because the exception happens when jQuery actually tries to set the attribute. Make sure that you *don't* set the attribute with the jQuery `attr()` function!
Pointy
A: 

I think you want to use this $(':submit')

It finds anything that acts as a submit button. See: http://api.jquery.com/submit-selector/

aptsurdist