March 26, 2012

Editing a row of data in a table using an id

Question by Tesh

I am stuck with finding a means of being able to edit a specific row in my table. I have so far managed to come up with add,delete and search for a specific item that is stored in my database, i base the delete on a id field. Currently i am using PHP and HTML, could someone please show me a simple example that retrieves data from a database which stores in a table and when a user selects edit. The row that has been selected for edit becomes editable and thereafter updated without duplicating the data.

CLARIFICATION OF My QUESTION

For Editing to work the UI must look like, when the edit button corresponding to particular row is clicked then all the columns with the data should get replaced with text boxes, i.e. row-wise edit form…

Thanks

Answer by Starx

This is a very vague question, involves a lot of things. Not, just php, mysql or html but mainly javascript. However I will give a simple example, since you must already be able to bring the data onto a table.

Suppose your <tr> structure is similar to this

<tr>
<td class="nameField"><span class="text">My name</span></td>
<td class="controls"><a class="edit">Edit</a></td>
</tr>

Now using jQuery for this

$('a.edit').click(function() {
    $(this).closest("tr").find("td").not(".controls").each(function(k,v) {
                       // ^ find all td but not the one with the controls
        var span = $(this).children('span');
        //get the elem holding the value

        $(this).append('<input type="text" value="'+span.text()+'" />');
        // Add a text box with the input inside the td
        span.hide();
    });
});

Demo

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!