Using jQuery to edit individual table cells

前端 未结 10 1993
心在旅途
心在旅途 2020-12-13 08:14

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 wi

10条回答
  •  被撕碎了的回忆
    2020-12-13 08:44

    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('')
          .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();
    

提交回复
热议问题