views:

46

answers:

2

I'm parsing a JSON response via $.ajax() and building a form from this object's values. The script I've written is long, but here's what it's doing:

  1. Dynamically creating:
    ~ a form element,
    ~ a fieldset element,
    ~ a button element,
    ~ 20 or so text inputs and label elements

  2. Appending the inputs and labels to the fieldset

  3. Appending the button to the fieldset

  4. Appending the fieldset to the form

  5. Appending the form to an element in the existing DOM.

Everything is working in all browsers except one small snippet in IE. I've narrowed it down to the following piece of code. (doc is a variable containing document)

fieldset.append(
    $(doc.createElement('button'))
        .addClass('ui-button')
        .attr('type', 'submit')
        .html('Re-Rate')
        .button()
);

This is step 3 from above. It creates a button element, adds a class, sets the type attribute to submit, gives it some text, and then appends it to the fieldset. IE fails with the error "Object doesn't support this action"

If I comment out the .attr() line like this:

fieldset.append(
    $(doc.createElement('button'))
        .addClass('ui-button')
        //.attr('type', 'submit')
        .html('Re-Rate')
        .button()
);

Everything works as expected.

If you're wondering, the .button() method is jQuery UI

+4  A: 

jQuery doesn't allow you to change the type of an <input> or <button> element.

The reason for this is consistency, and IE doesn't allow you to change the type once it's been inserted into the DOM.

Nick Craver
Interesting! Didn't know that. How would one dynamically create a `<button type="submit"></button>` ?
Stephen
Technically I haven't inserted it into the DOM yet...
Stephen
@Stephen - Correct, but jQuery disallows it in all cases, even though IE would be ok in your example. To create the element just create it with the element html: `$('<button type="submit" />')`
Nick Craver
A: 

jQuery won't let you modify the type attribute on an existing button element because IE throws an error when you try to do so.

However, you can try something like this (using jQuery 1.4's more concise element creation syntax):

fieldset.append(
  $('<button>', {'type': 'submit', 'class': 'ui-button', 'html': 'Re-Rate'}).button()
);
gabriel
You can't create an element like this, the syntax isn't valid, and if it were it'd throw an error. You can't have attributes in the HTML string *and* the property object (try it :)).
Nick Craver
Whoops, I've updated my answer so that it now works.
gabriel