Follow the below file to easily edit table records and submit that details in database using Ajax.
Note: When you double click the table value it converted like input field and once you change the text and click outside of the input it will automatically store using Ajax.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>how to save input when click outside of it in jquery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<table>
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
<tr>
<td class="editdata" data-id="1">Sample 1</td>
</tr>
<tr>
<td class="editdata" data-id="2">Sample 2</td>
</tr>
</tbody>
</table>
<script>
var currentEle = '';
$(document).on('dblclick', 'td.editdata', function(e) {
e.stopPropagation();
currentEle = $(this);
var tmp = $(this).text();
var id = $(this).attr("data-id");
$(this).html('<input type="text" id="tmp_edit" data-id="'+ id +'" value="' + tmp + '"/>');
$("#tmp_edit").focus();
});
$(document).click(function(e) {
if ($(e.target).closest('td.editdata').length == 0){
var name = $("#tmp_edit").val();
if (!name ){
alert('Please Submit The Valid Name');
setInterval('location.reload()', 100);
} else {
var id = $("#tmp_edit").attr("data-id");
$.ajax({
url: '/savedata',
type: 'post',
data: {
id: id,
name: name
},
dataType: 'json',
success:function(data) {
$(currentEle).html(data[0].name);
}
});
}
}
});
</script>
</body>
</html>
Total Views: 4,033