Search code examples
jqueryinputlivehtml

jQuery span to input and vice-versa


I have a problem. Look at the code bellow:

   $(function () {
    $('span').live('click', function () {
        var input = $('<input />', {
            'type': 'text',
                'name': 'aname',
                'value': $(this).html()
        });
        $(this).parent().append(input);
        $(this).remove();
        input.focus();
    });

    $('input').live('blur', function () {
        $(this).parent().append($('<span />').html($(this).val()));
        $(this).remove();
    });
    });

and html now:

<span>Click aici</span>

So, this it works, obviously, until jquery 1.8.3, inclusively. After 1.8.3 .live() is deprecated an we need to use .on(). So the code become:

$(function () {
    $('span').on('click', function () {
        var input = $('<input />', {
            'type': 'text',
                'name': 'aname',
                'value': $(this).html()
        });
        $(this).parent().append(input);
        $(this).remove();
        input.focus();
    });

    $('input').on('blur', function () {
        $(this).parent().append($('<span />').html($(this).val()));
        $(this).remove();
    });
    });

or just:

$(function () {
    $('span').click(function () {
        var input = $('<input />', {
            'type': 'text',
                'name': 'aname',
                'value': $(this).html()
        });
        $(this).parent().append(input);
        $(this).remove();
        input.focus();
    });

    $('input').blur(function () {
        $(this).parent().append($('<span />').html($(this).val()));
        $(this).remove();
    });
    });

But this is working just first time.

See demo here: http://jsfiddle.net/hW3vk/ So, any idea how to do that will be appreciated.

Thank you in advance.


Solution

  • $(function () {
        $(document).on('click', 'span', function () {
            var input = $('<input />', {
                'type': 'text',
                    'name': 'unique',
                    'value': $(this).html()
            });
            $(this).parent().append(input);
            $(this).remove();
            input.focus();
        });
    
        $(document).on('blur', 'input', function () {
            $(this).parent().append($('<span />').html($(this).val()));
            $(this).remove();
        });
    });
    

    You need to change the on parameters in order for it to work as live does

    $('(parent) static selector').on('event', 'dynamic selector', function(){...})
    

    Instead of $(document) you can use a parent selector so it will narrow down the travel

    Also here's a fiddle http://jsfiddle.net/Spokey/hW3vk/5/