Saswat
Saswat

Reputation: 12806

Error in inline edit code

I have a div html containing another nested div

<div class="draggable">
   <div class="edit_text">Hello</div>
</div>

Now i have a code where i am trying to edit the text of edit_text div

Here's my code

 if (key == 'edit') {
    alert('hii');
    //$(this).find('.edit_text').remove();
    var content = $(this).find('.edit_text').text();

    var width = $(this).width() - 1;
    var height = $(this).height() - 4;

    var $editbox = $("<input type='text'" +
        "style='width:" + width + ";" +
        "height:" + height + ";" +
        "border:none" +
        "' value='" + content + "' />");


    $(this).find('.edit_text').empty();
    $(this).find('.edit_text').prepend($editbox);
    $editbox.focus();
    $editbox.select();


    $($editbox).bind("blur",

    function () {
        $(this).find('.edit_text').html($($editbox).val());
        alert($($editbox).val());
        $($editbox).remove()
    });
}

issue is in this section

$(this).find('.edit_text').html($($editbox).val());
alert($($editbox).val());  
$($editbox).remove()

when i am clicking outside the div, the alert is displaying the $editbox.val()

but once the editbox is removed, the html of the innder div i.e. the edit_text is missing somewhat

what am i doing wrong?

Upvotes: 0

Views: 38

Answers (1)

sifriday
sifriday

Reputation: 4462

The $editbox is inside the .edit_text div. Your line of code:

$(this).find('.edit_text').html($($editbox).val());

is trying to look downwards in the DOM; in fact, you need to look up:

$(this).closest('.edit_text').html($($editbox).val());

That should also take care of removing the $editbox, so you can probably remove this line:

$($editbox).remove() 

Upvotes: 1

Related Questions