Kevin Le - Khnle
Kevin Le - Khnle

Reputation: 10887

Using the <button> tag and jQuery in IE8

I have a simple line of Javascript code

$('<button>').attr({ 'type': 'button' }).css({ 'cursor': 'pointer' }).text('Button').click(function  () { alert('clicked'); }).appendTo($('#btn'));

The html is even simpler

<div id='btn'>Click this button</>

Everything works when running this code FF as shown here on jsfiddle http://jsfiddle.net/kevinle/jJbNt/6/. But it fails to run on IE8.

What would be the explanation (has this problem been documented somewhere that I miss) and what would the work-around be?

Upvotes: 2

Views: 2268

Answers (6)

billrichards
billrichards

Reputation: 2060

This works for me for ie8

JQUERY:

$('button.buttonLink').click(function(){
  window.location = $(this).parent('a').attr('href');
});

HTML:

<a href="logout.php"><button class="buttonLink">LOGOUT</button></a>

Upvotes: 0

jfriend00
jfriend00

Reputation: 708036

You have a bunch of problems:

  1. Older versions of IE have some issues with the <button> tag which may or may not be your problem here.
  2. There is no type attribute on the button tag.
  3. You are missing a closing </div> in your HTML.
  4. You should use <input type="button"> instead.

See here: http://jsfiddle.net/jfriend00/e8eGW/ for a working version.

<div id='btn'>Click this button</div>

$('<input type="button" value="Button">').css({ 'cursor': 'pointer' }).click(function  () { alert('clicked'); }).appendTo($('#btn'));

Upvotes: 1

Kato
Kato

Reputation: 40582

just take out the .attr(...) and it will work fine (example).

button doesn't seem to have a type attribute that is visible in IE from javascript; you were thinking maybe of input?

Upvotes: 0

amustill
amustill

Reputation: 5302

It seems IE8 and older are having a problem parsing the 'type' attribute. Removing this or updating jQuery to 1.7 fixes solves the issue.

Upvotes: 0

Richard Neil Ilagan
Richard Neil Ilagan

Reputation: 14737

Maybe close your <div> element properly?

<div id='btn'>Click this button</div>

EDIT

OK, tested it out more thoroughly, and found that the call to .attr() was dumbing down IE's Javascript engine. After removing that from your jQuery chain, it worked in IE8.

If you think about it, since you're instantiating a <button> anyway, you don't need to set it's type to "button".

$('<button>')
    //.attr({ 'type': 'button' })
    .css({ 'cursor': 'pointer' })
    .text('Button')
    .click(function  () { 
        alert('clicked'); 
    })
    .appendTo('#btn')
    ;

http://jsfiddle.net/9xUj5/

Upvotes: 3

christian.thomas
christian.thomas

Reputation: 1122

Try http://jsfiddle.net/jJbNt/16/ - Shouldn't really make a difference, try it though.

Upvotes: 0

Related Questions