开发者

Changing the cell contents of a table using input forms

开发者 https://www.devze.com 2023-02-08 14:18 出处:网络
For practice with Javascript, I created a table where based on what cell you clicked, it changes the background color of that cell. Now I\'m trying to setup my table, so that when you click on a cell,

For practice with Javascript, I created a table where based on what cell you clicked, it changes the background color of that cell. Now I'm trying to setup my table, so that when you click on a cell, it opens an input box where you change the contents of the cell. What I thought would be a 10 min project as turn to an hour of figuring it out. A开发者_Go百科ny help or ideas would be helpful. Thanks!!


It would be helpful if you provided the code you're working with so far.

Here's a generic example where the TD contains one input and one text node.

Working example: http://jsfiddle.net/NCQv2/

html

<table>
    <tr><td>CLICK HERE<input></td></tr>
</table>

css

input {
    display:none;
}

javascript

var td = document.getElementsByTagName('td')[0];

td.onclick = function(e) {
    var e = e || event;
    var target = e.target || e.srcElement;
    if( target.nodeName !== "INPUT" ) {
        var input = this.getElementsByTagName('input')[0];
        if( input && input.style.display !== 'inline' ) {
            input.style.display = 'inline';
            input.value = this.firstChild.data;
            input.previousSibling.data = '';
            input.focus();
        }
    }
};

td.getElementsByTagName('input')[0].onblur = function() {
    this.previousSibling.nodeValue = this.value;
    this.style.display = 'none';
};


Not too tough. Here's a working sample.

http://jsfiddle.net/B5rvp/2/

$('td').click(function(){
    var answer = prompt("Enter New Value", '');
    $(this).html( answer );        
});
0

精彩评论

暂无评论...
验证码 换一张
取 消