I have a form, and I want to be able to edit any part of that form by double clicking it. So going from this:
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
<tr>
<td>John Smith</td>
<td>[email protected]</td>
<td>+12345678</td>
</tr>
</table>
I have a form, and I want to be able to edit any part of that form by double clicking it. So going from this:
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
<tr>
<td>John Smith</td>
<td>[email protected]</td>
<td>+12345678</td>
</tr>
</table>
How can I by double-clicking an element, transform it to an input element?
For example: if I double click on John Smith
, the HTML changes into this:
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
<tr>
<form action="index.php" method="post">
<td><input type="text" value="John Smith" name="name" /></td>
<td>[email protected]</td>
<td>+12345678</td>
</form>
</tr>
</table>
So now I can change John's name.
Does someone know how to do it?
Share Improve this question asked Feb 25, 2018 at 20:14 SanChampSanChamp 5281 gold badge6 silver badges11 bronze badges 2 |3 Answers
Reset to default 12Try this, fields from the second row are editable with dblclick
document.querySelectorAll("table tr:nth-child(2) td").forEach(function(node){
node.ondblclick=function(){
var val=this.innerHTML;
var input=document.createElement("input");
input.value=val;
input.onblur=function(){
var val=this.value;
this.parentNode.innerHTML=val;
}
this.innerHTML="";
this.appendChild(input);
input.focus();
}
});
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
<tr>
<td>John Smith</td>
<td>[email protected]</td>
<td>+12345678</td>
</tr>
</table>
How about that:
<table>
<tr>
<th>Name</th>
<th>Email</th>
<th>Phone</th>
</tr>
<tr>
<td id="name">John Smith</td>
<td>[email protected]</td>
<td>+12345678</td>
</tr>
</table>
<script>
$("#name").dblclick(function(e) {
if (e.target.parentElement.nodeName != 'form') {
var form = $('<form action="index.php" method="post">');
var parent = $(e.target.parentElement);
parent.children().each(function(i, elem){
form.append(elem);
})
parent.empty();
parent.append(form);
}
})
</script>
It handles double click event and wraps all <td>
elements inside <tr>
into <form>
tag.
I believe this will do what you want:
$("document").ready(function () {
var haveForm = false;
$("td").dblclick(function () {
var thisVal = $(this).html();
if (!haveForm) {
$("td").wrapAll('<form action="index.php" method="post" />');
haveForm = true;
}
$(this).html('<input type="text" value="' + thisVal + '" name="name" />');
});
});
jsFiddle
This makes use of jQuery's wrapAll()
and safe guards against multiple form
elements being created.
<td>
's) in aform
initially? – wmash Commented Feb 25, 2018 at 20:25