I have a table of inputs that are read only, and these are populated from a DB. A user is going to be able to double-click on a cell and activate it for editing. In order to send the new data to the DB the user must press a button. The user can also double-click another cell after activating one, and that is my problem. I want to be able to replace the original value of the cell if the focus was lost to something else other than the button.
I have this fiddle that represents my problem.
HTML:
<table>
<tr>
<td><input id="1" type="text" value="Data 1" readonly="readonly"/></td>
<td><input id="2" type="text" value="Data 2" readonly="readonly"/></td>
<td><input id="3" type="text" value="Data 3" readonly="readonly"/></td>
<td><input id="4" type="text" value="Data 4" readonly="readonly"/></td>
</tr>
</table>
<button>Send</button>
JavaScript:
$(document).ready(function(){
var element = null;
$('input').dblclick(function(){
$(this).data("backup",$(this).val())
if(element == null){
$(this).toggleClass("active");
$(this).blur(function(event){
window.setTimeout(function(){
if(!$('button').is(':focus')){
$(this).val($(this).data("backup"));
//alert("button has no focus");
}
},100);
});
$(this).attr('readonly',!$(this).attr('readonly'));
element = $(this);
}
else{
if(element.attr('id') == $(this).attr('id')){
$(this).toggleClass("active");
$(this).attr('readonly',!$(this).attr('readonly'));
element = null;
}
else{
element.toggleClass("active");
element.attr('readonly',!element.attr('readonly'));
$(this).toggleClass("active");
$(this).blur(function(event){
window.setTimeout(function(){
if(!$('button').is(':focus')){
$(this).val($(this).data("backup"));
//alert("button has no focus");
}
},100);
});
$(this).attr('readonly',!$(this).attr('readonly'));
element = $(this);
}
}
});
$('button').click(function(){
var value = $('tr').find('.active');
var data = value.val();
alert(data);
});
});