Skip to content

Instantly share code, notes, and snippets.

@thewinterwind
Created November 9, 2013 08:40
Show Gist options
  • Save thewinterwind/7383177 to your computer and use it in GitHub Desktop.
Save thewinterwind/7383177 to your computer and use it in GitHub Desktop.
Convert span to text input for editing, then back to span upon successful save
// Icons with edit class will convert their data partner to an input
$('i.edit').click(function() {
var table = $(this).data('table');
var column = $(this).data('column');
var relation = $(this).data('relation');
var id = $(this).data('id');
var type = $(this).data('type');
var morph = $(this).data('morph');
var original_elem = $(this).siblings('span');
var original_text = original_elem.text();
var new_elem = original_elem.html('<input class="injected" type="text" data-morph="' + morph + '" data-table="' + table + '" data-column="' + column + '" data-relation="' + relation + '" data-type="' + type + '" data-id="' + id + '">');
new_elem.find('input').focus();
// If JS injected inputs are blank on blur event, then rollback any HTML changes, else, save new value to DB
$('.injected').blur(function() {
$(this).parent().html(original_text);
});
});
// Add a tooltip letting the user know to push Control+Return to save
$('.injected').tooltip();
// Control and Return key mappings, respectively
var map = { 17: false, 13: false };
// When the user presses Control + Return when an input.injected has a value, the AJAX saving event fires
$(document).keydown(function(e) {
if (e.keyCode in map) {
map[e.keyCode] = true;
if (map[17] && map[13]) {
if ( $.trim( $('.injected').val() ) !== '') {
var value = $('.injected').first().val();
var table = $('.injected').data('table');
var column = $('.injected').data('column');
var id = $('.injected').data('id');
var morph = $('.injected').data('morph');
var type = $('.injected').data('type');
$.ajax({
type: "POST",
url: "/ajax",
data: {
value: value,
table: table,
column: column,
id: id,
morph: morph,
type: type
}
})
.done(function(result) {
$('.injected').closest('span').html(result);
});
}
}
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment