With the code:
<table>
<tr><td contenteditable>My_Name</td><td>Surname</td></tr>
<tr><td contenteditable>My_Name2</td><td>Surname2</td></tr>
</table>
You can edit a cell in an HTML table. My problem is when I edit the cell and press enter, it creates a new line in cell. What I really would like is, if I press enter I go to the cell just below that cell I just edited so that I can edit that cell.
Currently I have to use the mouse to go to the next cell, but if I can press enter and go to the cell, it will help me edit the cells a bit faster. Plus the updated data will be stored in my database, so I also don't want unnecessary space stored in the database.
But I am not sure what I can do. Is there any example I can look at?
You have to understand that 'contenteditable' is making your markup behaving like a
<textarea>
. Normally, people press the tab key to skip from a form field to another.Using jQuery javascript library, you can read the keyboard for enter key, javascript it to 'escape' the edition by setting focus somewhere else, perhaps the next td with contenteditable. :
jsFiddled here
Demo showing how to capture and
preventDefault
action on enter key press.Here's the code that does the trick:
I've built a fully editable table "Grid" in JS and HTML before.. and logic behind it simply is as following: 1- in your table after you layout all your cols, add an action col and add a "edit" link in each row that points to an Edit function, in this Edit link pass the row index so.. it will look like that:
2- your Edit function will simple loop on your columns using that rowIndex and replace the text values with a text box tag
Just avoid making the "Edit" column Editable
now, you should have a fully editable row.. on last thing, is to Add beside the "Edit" link a "Cancel" link that will loop again on the Row columns like the Edit link and Replace the Text tags with a Span or just pure html with the "" original values..
You may wonder how I will have the origianl td values, well in this case we added a hidden field that carrys the td value, so when the user click cancel after edit. we get the cell original value before edit,
hope that helps.
Disclaimer: This code requires JQuery.
Something like this? http://jsfiddle.net/v2Tdn/3/
* UPDATE *
Note, I've updated the jsfiddle to also select the text when you press enter. For the previous example which only focused on the next TD, please use http://jsfiddle.net/v2Tdn/1/ .