Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
378 views
in Technique[技术] by (71.8m points)

html - Using jQuery to edit individual table cells

How can I use jQuery to click on a table cell and edit its contents. There is a particular column which contains several paragraphs of data, so if possible, have a pop up window with a large text area (or ideally an HTML editor).

The changes need only be superficial as I am using another jQuery plugin to scrape the table contents and export it to something else.

Difficulty, none of the cells can have unique names or id's.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Seeing as how this page is both 3 years old and the first result in a Google search I thought it was due a more current answer. Given the weight and complexity of the plugin options above I thought a simpler, no-frills, more direct solution might also be appreciated for those looking for alternatives.

This replaces the table cell with a text input and calls custom events so you can handle whatever use case you want on save, close, blur, etc...

In this case the only way to change the information in the cell is to press enter, but you can customize that if you like, eg. you might want to save on blur.

In this example you can also press the Esc key to stop editing and put the cell back to what it was. You can customize that if you like.

This example works on a single click, but some people prefer doubleclick, your choice.

$.fn.makeEditable = function() {
  $(this).on('click',function(){
    if($(this).find('input').is(':focus')) return this;
    var cell = $(this);
    var content = $(this).html();
    $(this).html('<input type="text" value="' + $(this).html() + '" />')
      .find('input')
      .trigger('focus')
      .on({
        'blur': function(){
          $(this).trigger('closeEditable');
        },
        'keyup':function(e){
          if(e.which == '13'){ // enter
            $(this).trigger('saveEditable');
          } else if(e.which == '27'){ // escape
            $(this).trigger('closeEditable');
          }
        },
        'closeEditable':function(){
          cell.html(content);
        },
        'saveEditable':function(){
          content = $(this).val();
          $(this).trigger('closeEditable');
        }
    });
  });
return this;
}

You can selectively apply the editable cells by attaching them like so, or whatever makes sense for your case.

$('.editable').makeEditable();

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...