jbills
jbills

Reputation: 694

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?

Upvotes: 0

Views: 496

Answers (3)

AaronShockley
AaronShockley

Reputation: 851

$(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/

Upvotes: 0

josh.trow
josh.trow

Reputation: 4901

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/

Upvotes: 0

pepkin88
pepkin88

Reputation: 2756

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.

Upvotes: 1

Related Questions