Monday, March 23, 2009

Dynamically creating input box/checkbox/radio button... does not work in Internet Explorer (IE)

While working on some project, trying to create a checkbox and radio button dynamically using jQuery I came across a problem. Mozilla Firefox, Opera and Safari were creating and rendering my new checkboxes just fine, but Internet Explorer (IE6, IE7) did not create them. I spend half a day trying to figure out what is wrong with my jQuery or JavaScript code. Some hours later, I remember, I came across a post saying that IE can not create a general DOM input form element and then assign it a type (checkbox, radio, text, password, etc) attribute.

What you need to do when you are creating a new checkbox or radio button set with jQuery is to define the type attribute while creating like so:

$('<input type="checkbox" />');
// Create and then set any other attributes
$('<input type="checkbox" />').attr('id', 'newBox');

Problem:

Can not create a new input form fields using jQuery or newly created checkboxes and radio buttons are not displayed/created.

Solution:

To solve the problem you need to create an input field with type attribute already defined.

6 comments:

  1. this doesnt work eg

    $('[input type="text"/]').attr('name' , name ).attr('id' , 'aw_'+name).appendTo( WebArt.frm );

    replace [ and ] as this post wont accpert HTML tags

    ReplyDelete
  2. Thanks for the tip. I had to remove all of my .attr calls when adding a radio box input, because IE6 was ignoring all attributes I added using .attr. The main issue was that IE6 was ignoring my onclick attribute until I added it directly like the above post demonstrates with the type attribute example.

    ReplyDelete
  3. when input type is "hidden", then it seems to work well with IE, "checkbox" -no. note for myself: use jQuery as much as possible.

    ReplyDelete
  4. thank you very much!
    I found similar problem with IE - when creating button element and assigning onClick attribute to this it will not work - solution use like this:

    $("<button onClick='del_row(this)'>")

    ReplyDelete
  5. The main issue was that IE6 was ignoring my onclick attribute until I added it directly like the above post demonstrates with the type attribute example.

    ReplyDelete
  6. You can create an input object and set the type like so:
    $('[input/]')
    .attr('type', input type here)
    .appendTo($("$parent"));

    ReplyDelete