Skip to content

Instantly share code, notes, and snippets.

@crobinson42
Last active August 29, 2015 14:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crobinson42/20117599134799489e54 to your computer and use it in GitHub Desktop.
Save crobinson42/20117599134799489e54 to your computer and use it in GitHub Desktop.
(jQuery) Edit Element in-place
// ****Copy and paste in script tags in an empty HTML page****
//
// - When you click on a button it turns into an input field,
// - you can edit the text and press "enter" to switch back
// - to a button
//
$(document).on('ready', function() {
// Make buttons and append it to the DOM
$('body').prepend('<button class="button">This is a Button!</button>');
$('body').prepend('<button class="button">Boom</button>');
$('body').prepend('<button class="button">Another Button</button>');
// Set a click listener on the buttons
$(document).on('click','.button',function(){
// store reference to "owner object"
var $el = $(this);
// store jquery object for imput
var $input = $('<input type="text" name="input"/>');
// set the input box text to existing button text
$input.val($el.text());
// replace button with input element
$el.replaceWith($input);
// Set listener for keypress
$(document).on('keypress',function(e){
// Check if "enter" key is pressed
if(e.which == 13) {
// store a jquery button object in variable
var $btn = $('<button class="button"></button>');
// get the text from the input and set button text
$btn.text($('input').val());
// replace input with button
$('input').replaceWith($btn);
}
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment