Search code examples
javascriptjqueryhtml-tabletextbox

Create text box on click


Initially when the page loads the table will be displayed normally but when I click on the edit label it should make the first name value as text box to make it editable. I will enter the value and hit enter it will submit the form. I am really confused how to achieve this.

This is the sample table I have, I couldn't go beyond this.

<label id="edit" style="cursor:pointer; color:blue;">edit</label>

<table>
    <tr><td>First Name: </td>
        <td>John</td>
    </tr>
    <tr><td>Last Name: </td>
        <td>Wright</td>
    </tr>
</table>

jsfiddle


Solution

  • $('#edit').click(function() {
        var $table = $('table');
        if ($table.find('input').length) return;
        $table.find('td:nth-child(2)').html(function(i, v) {
            return '<input value=' + v + '>';
        })
    })
    
    $('table').on('blur', 'input', function() {
        $('table input').replaceWith(function() {
            return this.value;
        })
    })
    

    http://jsfiddle.net/cnuDh/