peace_love
peace_love

Reputation: 6461

How can I restore the width of editable cell?

I have editable cells and when I click inside the table cell, the cell width is getting wider, but when I leave the cell, then I want my table to return to the normal width. Because otherwise the sign is much too far away from the price.

    // Editable Cells

    $(document).on('click', '.editable', function(event) {
            if ($(this).children("input").length > 0)
                return false;
            var tdObj = $(this);
            var preText = tdObj.html();
            var inputObj = $("<input type='text' />");
            tdObj.html("");
            inputObj.width(tdObj.width())
                .height(tdObj.height())
                .css({
                    border: "0px",
                    width: "30%",
                })
                .val(preText)
                .appendTo(tdObj)
                .trigger("focus")
                .trigger("select");
            inputObj.keyup(function (event) {
                if (13 == event.which) { // press ENTER-key
                    var text = $(this).val();
                    tdObj.html(text);
                } else if (27 == event.which) { // press ESC-key
                    tdObj.html(preText);
                }
            });
            inputObj.click(function () {
                return false;
            });
        });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<table style="width:100%">
  <tr>
    <th>Firstname</th>
    <th >Price</th>
    <th>Lastname</th> 
  </tr>
  <tr>
    <td>Jill</td>
    <td><span class="editable">50</span> €</td>
    <td>Smith</td> 
  </tr>
  <tr>
    <td>Eve</td>
    <td><span class="editable">50</span> €</td>
    <td>Jackson</td> 
  </tr>
</table>

Upvotes: 0

Views: 32

Answers (1)

Daniel Lagiň
Daniel Lagiň

Reputation: 728

Put this in your click function:

inputObj.blur(function(event) {
    tdObj.html(preText);
});

Code:

$(document).on('click', '.editable', function(event) {
    if ($(this).children("input").length > 0)
        return false;
    var tdObj = $(this);
    var preText = tdObj.html();
    var inputObj = $("<input type='text' />");
    tdObj.html("");
    inputObj.width(tdObj.width())
        .height(tdObj.height())
        .css({
            border: "0px",
            width: "30%",
        })
        .val(preText)
        .appendTo(tdObj)
        .trigger("focus")
        .trigger("select");
    inputObj.keyup(function (event) {
        if (13 == event.which) { // press ENTER-key
            var text = $(this).val();
            tdObj.html(text);
        } else if (27 == event.which) { // press ESC-key
            tdObj.html(preText);
        }
    });
    inputObj.blur(function(event) {
        tdObj.html(preText);
    });
    inputObj.click(function () {
        return false;
    });
});

Upvotes: 1

Related Questions