Dynamic text box list
I am trying to make a text box list using jquery. What I want is to have text that changes into a textbox when clicked. Then I want it to return to text afterwords. My problem is getting the dynamically created textboxes to focus, change the textbox text, be removed and change the text. This is my code:
$('.l').click(function() {
$('<input type="text" id="ltb" class="'+$(this).attr("class")+'">').insertAfter($(this)).val($(this).val());
$('#ltb').focus();
$(this).remove();
})
$('#ltb').blur(function() {
$('<div id="'+$(this).attr("开发者_如何学运维class")+'" class="l">'+$(this).val()+'</div>').insertAfter($(this));
$(this).remove();
});
.l is the text while #ltb is the textbox. I need the #ltb to change value, focus, and be removed. I need .l to change once #ltb is removed. Can someone tell me how to do this?
Instead of .click(function () {})
use .live('click', function () {})
or .delegate('click', function () {})
. Analogically to .blur()
.
This is necessary because elements are dynamically added to the document and don't have added event listener to them.
A working revision here - notice (as pepkin said) the live
, also I moved the removal of the input text area.
http://jsfiddle.net/TrowthePlow/Yp6Yj/1/
$(document).ready(function () {
$('.l').live('click', function () {
$(this).replaceWith('<input type="text" id="ltb" class="' + $(this).attr('id') + '" value="' + $(this).text() + '" />');
$('#ltb').focus().select();
});
$('#ltb').live('blur', function () {
$(this).replaceWith('<div id="' + $(this).attr('class') + '" class="l">' + $(this).val() + '</div>');
});
});
http://jsfiddle.net/psw4d/
精彩评论