最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Add a row to a table in Javascript that contains input classes - Stack Overflow

programmeradmin4浏览0评论

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);
发布评论

评论列表(0)

  1. 暂无评论