Search code examples
javascriptjquerydom-manipulation

How to change a label to textfield with jQuery when its respective link is clicked?


I have a table and I need that when a particular span is clicked, the span before it changes from a label to a text field. The following is the table:

<table>
    <tbody>
        <tr>
            <td><span class="spanName">John Doe</span>&nbsp;<span class="spanDefaultName">Alter</span></td>
        </tr>
        <tr>
            <td><span class="spanName">Jayne Doe</span>&nbsp;<span class="spanDefaultName">Alter</span></td>
        </tr>
    </tbody>
</table>

Now lets say that the Alter after John Doe is clicked, the span before it has to change from just John Doe to a textfield (This applies also for all the others). This is how the result will look like if John Doe's alter span is clicked:

<table>
    <tbody>
        <tr>
            <td><span class="spanName"><input type="text" /></span>&nbsp;<span class="spanDefaultName">Alter</span></td>
        </tr>
        <tr>
            <td><span class="spanName">Jayne Doe</span>&nbsp;<span class="spanDefaultName">Alter</span></td>
        </tr>
    </tbody>
</table>

If possible, and I think it is possible with jQuery by using :next or something of this sort, I have to implement this with using just classes and not IDs.

Also, if you think that I should use an anchor instead of a span, please let me know. I am using a span simply because of the :next and :previous functionalities in jQuery.

Any help would be greatly appreciated


Solution

  • Something like this:

    $(".spanDefaultName").click(function() {
        var text = $(this).prev("span").text();
        $(this).prev("span").hide();
        $(this).before('<input value="' + text + '" />');
        $(this).unbind("click");
    });
    

    Demo: http://jsfiddle.net/karim79/MWwyR/4/