admin管理员组

文章数量:1384803

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

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

Share Improve this question asked Jan 30, 2009 at 11:44 joe90joe90 5382 gold badges5 silver badges19 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

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

Try using innerHtml property of element.

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

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./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./plog/creating-dom-element-with-jquery

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

本文标签: Add a row to a table in Javascript that contains input classesStack Overflow