I want to write an event where user double clicks on table cell and the cell is updated with an HTML form. While the form is showing, I don’t want the double-click event to be operational. If user cancels the form by pressing Cancel, or submits the form by pressing Submit, the table cell should update to original or the updated value respectively, and the double-click event should work again.
How can this be done?
This is what I currently have. If you double-click on "click me" you will see a form show up. If you double-click on the form again, you will see the form update again, because the double-click event is still being triggered while the form is showing.
How can I only trigger the double-click event when my cell is showing value, and there is no HTML form being shown.
Just to clarify, this will be a cell that will store a single float value, which can be updated if I first double-click the value, and then press Submit, or cancelled by pressing Cancel, in which case the cell updates to its original value and you can double-click that value again.
function renderMultEditBox(id, mult) {
$('#mult_1').html($('#mult_1').html() + '<h2>Title Text</h2><form><input type="text" name="a"><input type="text" name="b"><button type="button"><b>Cancel</b></button>');
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border="1">
<tr>
<td style="text-align: right; cursor: pointer;" id="mult_1" ondblclick="renderMultEditBox(this.innerHTML)">double-click me</td>
</tr>
</table>
3
Answers
The easiest way to do this is probably to just put the form and the table cell content in a separate
<div>
s inside the<td>
, then you can toggle their visibility:Here is how I would do it.
First thing is to have that form already in DOM, but hidden. So it is easier to use it many times and/or many places.
Then, on dbl click in a cell, you clone that form, remove the hiding class and insert it into the cell. So it is much acting like a template.
Look for jQuery clone for more… Because you can also clone the event handlers for the buttons… Which will reduce code duplations. Needs 5 min more reading to achieve 😉
Check if the cell has form by
if (target.find('form').length > 0) return
Clone original value by
target.clone().html()