I’m working on a simple admin system. Now I want to make it easier for admin to edit data. My goal is, when an element is double-clicked, it will change to input. Then after editing, if the admin clicks outside of the input, it runs an event to run ajax. It is like the system in PHPMyAdmin, when we want to edit data, just double click at the data.
HTML
<tbody>
<tr>
<th scope="row">1</th>
<td class="editable" name="email">[email protected]</td>
<td class="editable" name="username">this_is_username</td>
<td class="editable" name="name">My Name</td>
</tr>
</tbody>
JavaScript
$(".editable").dblclick(function () {
const id = $(this).data("id");
const col = $(this).attr("name");
$(this).html(
"<form>
<input class="editing" type='text' value='" + $(this).val() + "'>
</form>"
);
});
// I want this Ajax will execute whene other side is clicked
$.ajax({
url: "http://localhost/myProject/myController/myMethod",
type: "post",
data: {
id: id,
col: col,
value: $('.editing').val()
},
success: function () {
document.location.href = "http://localhost/myProject/myController";
},
});
Controller
public function myMethod()
{
$id = $this->input->post("id");
$col = $this->input->post("col");
$value = $this->input->post("value");
$this->db->set($col, $val);
$this->db->where('id', $id);
$this->db->update("my_table");
}
But I do not know how to make an event to execute Ajax when admin click outside of the input. Anybody can help me? Or there are function have been made?
***Note: I want to exclude it on tag anchor. So, when some link is pressed, it does not execute the Ajax, but go to the link.
2
Answers
Use onblur event of input element. It will fire when user focus out from the input field.
Since you are using jQuery, hook the on blur event, like so:
The blur event is fired when the element that you attached it to loses focus, but is does not trigger by bubbling, only for the specific element.
Lookup more info for blur or maybe focusOut