I am trying to create a table of elements in HTML, and then when an edit button (which would be next to the row you would want to edit) is pressed it would turn the text elements into <input>
elements.
However, after you enter values into the input fields and press the edit button again (saving your changes), it is supposed to make the original text elements contain the ones entered into the input field.
I have also tried using the text()
function, and that also returns empty.
This is my HTML…
<table>
<tr id='0'>
<td id='editable' style="border:1px solid #000;padding:7px">Title</td>
<td id='editable' style="border:1px solid #000;padding:7px">0 mins</td>
<td id='editable' style="border:1px solid #000;padding:7px">Genre</td>
<td id='editable' style="border:1px solid #000;padding:7px">[]</td>
<td id='editable' style="border:1px solid #000;padding:7px">0</td>
<td>
<button id="editButton" style="background-color:#ADD8E6" />🖉
</td>
</tr>
</table>
And this is my jQuery…
$("#editButton").click(function() {
if ($(this).attr('id') === "editButton") {
$(this).parent().parent().children("#editable").html("<input type='text' id='editable'/>");
$(this).attr("id", "saveable")
} else {
$(this).parent().parent().children("#editable").each(function(i) {
$(this).html("<td>" + $(this).val() + "</td>")
})
$(this).attr("id", "editButton")
}
});
I have been testing this on JSFiddle: https://jsfiddle.net/ajecdm5n/1/.
Also, if there are any improvements I can make, please do tell me.
2
Answers
Firstly, an
id
should be a unique identifier for one element on the page, whereas you have several with the same ID. If you need many elements to have the same identifier then it’s better to give them aclass
instead.Next, your
#editable
elements are your<td>
elements as well as your editable text field – so the actual rendered HTML assumedly looks like<td id='editable'><input type='text' id='editable' />
. This is causing issues in your for loop because you are setting thehtml
on the<td>
first – which removes the<input>
– then trying to loop onto the input. In addition,<td>
doesn’t have a.val()
, so this is why your method call is empty.You may also wish to consider using data properties to store whether it’s an edit button or not, as I think changing the ID can be problematic.
Perhaps something like this may be better?
Update fiddle link
https://jsfiddle.net/pymftrdw/2/