Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html table editable

I have a very simple table structure

<table width='50%' id='tabs'>
<tr><td>1</td><td>5</td><td>6</td></tr>
<tr><td>2</td><td>2</td><td>2</td></tr>
<tr><td>3</td><td>2</td><td>2</td></tr>
</table>

and here is my simple script to make table editable this is working fine but i found that it is slow and code is not efficient.I would like to improve this code.By the way i am working with jquery 1.3.2

var z={};
function tdClicks(){
var x="",y="";
$("table tr td").click(function(){
    z=$(this);
    x = $(this).text() || $(this).find("input[type='text']").val();
    if(!x){
        x="";
    }
    $(this).html("<input type='text' size='5' value='"+ x+"' />");
    $(this).unbind("click");
    $(this).find("input[type='text']").bind("blur", function(){
        catchme($(this).val());
        tdClicks();
    });
});
}

function catchme(wht){
    $(z).text(wht);
}

tdClicks();

Please see JS FIDDLE HERE

like image 442
Murali N Avatar asked Mar 21 '13 12:03

Murali N


2 Answers

try this

$("table tr td").on('blur',"input[type='text']", function( e ){

    $(this).closest('td').text( 
        $(this).val()
    );
});

$("table").on('click','td', function( e ){

   if ( $(this).find('input').length ) {
       return ;   
   }    

   var input = $("<input type='text' size='5' />")
                  .val( $(this).text() );

   $(this).empty().append( input );

});

and you can find it fiddle http://jsfiddle.net/v7znh/13/


I have updated code for jquery 1.3, as user comment

$("table td").click( function( e ){

    if ( $(this).find('input').length ) {
         return ;   
    }        
    var input = $("<input type='text' size='5' />")
                      .val( $(this).text() );

    $(this).empty().append( input );

    $(this).find('input')
           .focus()
           .blur( function( e ){
                  $(this).parent('td').text( 
                     $(this).val()
                  );
            });    
});

check this http://jsfiddle.net/v7znh/16/

like image 82
rab Avatar answered Sep 18 '22 19:09

rab


This seems a bit cleaner

$("table").on("click", "td:not(.active)", function () {    
    var $this = $(this);
    var $textbox = $("<input>", { type: "text", size: 5, value: $this.addClass("active").text() });
    $this.html($textbox);
    $textbox.focus();    
});

$("table").on("blur", "input:text", function () {        
    var $this = $(this);
    $this.parent().removeClass("active").text($this.val());
});

http://jsfiddle.net/hunter/v7znh/12/

like image 40
hunter Avatar answered Sep 20 '22 19:09

hunter