Link to home
Create AccountLog in
Avatar of tonelm54
tonelm54

asked on

Change div to textbox to div and then back

Im trying to make a simple script to allow a user to select a div, which changes into a textbox, and allows update.

Ive managed to get the change from a div to a textbox, but cant seem to figure out how to change back into a div. Once Ive got the value I can update it (hopefully).

So my code soo far is:-
$(document).ready(function() {
    $('.lblTextboxUpdate').click(function() {
        $(this).removeClass('.lblTextboxUpdate');
        var html = $('#contentbox').html();
        $(this).html($('<input class="textboxLblUpdate" type="text" />').attr('id', $(this).id)attr('id', $(this).name).val(html));
        $('#contentbox').replaceWith(textarea);
    });
    $('.textboxLblUpdate').blur(function() {
        $(this).removeClass('.textboxLblUpdate');
        $(this).parent().addClass('.lblTextboxUpdate');
        $(this).html($(this).find('input').val());
    });
});

Open in new window



Which seems to work on my code, but doesnt change back to a div when lost focus (blur).
<div class="lblTextboxUpdate" id="contentbox">hello</div>
<div>Bye</div>

Open in new window


Any advise?
ASKER CERTIFIED SOLUTION
Avatar of Jon Norman
Jon Norman
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
Create an account to see this answer
Signing up is free. No credit card required.
Create Account
Let me explain:

The code that you had would not work because the textarea was not there when the onblur event handler was being added to it. What you can do is assign the event handler to the document element (which will exist), it will only fire for anything that matches the selector in the second argument.

Secondly I have changed it so that a textarea is created rather than an input of type text, and I have entirely replaced the div with the textarea and vice versa as it's very bad practice to have more than one thing of the same id.
Maybe you already know that there is a jquery plugin available that is similar to what you are trying to accomplish.

http://www.appelsiini.net/projects/jeditable