tags:

views:

731

answers:

3

Im trying do this basically:

    var tr = document.createElement("tr");
 var td = document.createElement("td");
    td.appendChild(document.createTextNode('<input class="param" type="text" name="dummy" value="fred"/>'));
    tr.appendChild(td);

but it just displays the input... as normal text, how do I insert it so that it works as i require..?

im guessing its the createTextNode that needs to be changed?

Cheers

+1  A: 

Try using innerHtml property of element.

That is try using td.innerHtml = "<input ...../>"

Rutesh Makhijani
+4  A: 

You could either

td.innerHTML = '<input class="param" type="text" name="dummy" value="fred"/>';

or

var ip = document.createElement( 'input' );
ip.className = 'param';
ip.type = 'text';
ip.name = 'dummy';
ip.value = 'fred';

td.appendChild( ip );

EDIT

ie won't allow the type of a form element to be changed dynamically. I'm pretty sure this only applies when the element already has a type and has already been inserted into the DOM. Best to check though. If it doesn't work use method 1

meouw
you can set the type and the name attribute before you add it to the DOM in IE but after you can't change it or reference the element in JS by name.
scunliffe
+1  A: 

Meouw has the right idea. You're creating a text node in your example, and what needs to be done is create a dom element.

This is also another case where jQuery could simplify your code. What you were attempting to do by adding the element as an html string can be done with the jQuery html( val ) function:

http://docs.jquery.com/Attributes/html#val

Basically, to apply this technique with your given example, you would include the jQuery library on your page and write the following line:

$("#someTable").html('<tr><td><input class="param" type="text" name="dummy" value="fred"/></td></tr>');

You can also create any html element on the fly and string together attributes and event handlers in one line as in the following example:

http://www.peterbe.com/plog/creating-dom-element-with-jquery

var textbox = $("<input type='text'></input>").attr('name','dummy').addClass('param').val('fred');
$("#someTableCell").append(textbox);
Rich