Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQuery Autocomplete doesn't work when replacing a SPAN to an INPUT

I have an input field which is using the autocomplete function. When I only do this, the autocomplete works. But: I want to display a span and replace it for an inputbox when a user clicks on it. Unfortunately, the autocomplete function breaks. Considering the following code:

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

    $('#my_input').live('blur', function () {
        $(this).parent().append($('<span />' , {'id': 'my_span'}).html($(this).val()));
        $(this).remove();
    });
});

$("#my_input").autocomplete({
        source: function(req, resp) {
            $.getJSON("http://localhost/grootjeframework/testproject/json/find/partij/naam/" + encodeURIComponent(req.term), resp);
        },

        select: function(event,ui){
             //do Stuff
        }
    }); 

(the editor considers my HTML span as a span element ;) so I can't post it. For your information: its just a normal span with an ID 'my_span')

The replacement of the input and span works fine. The autocomplete, without the replacement scripts, works also fine. But, combining both, the autocompletefunction breaks.

like image 648
Eminentie Steef Avatar asked Dec 05 '25 16:12

Eminentie Steef


1 Answers

'my_input' is created only on 'my_span' click, so when you attach 'blur' event handler on it and autocomplete plugin it doesn't exist yet.

Try doing something like this:

$(function () {

    $('#my_span').live('click', function () {
        var input = $('<input />', {'type': 'text', 'id': 'my_input', 'name': 'my_input', 'value': $(this).html()});

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

        input.autocomplete({
            source: function(req, resp) {
                $.getJSON("http://localhost/grootjeframework/testproject/json/find/partij/naam/" + encodeURIComponent(req.term), resp);
            },

            select: function(event,ui){
                 //do Stuff
            }
        }); 

        $(this).parent().append(input);
        $(this).remove();
        input.focus();
    });

});

This way you attach event handler and autocomplete on element after it's creation.

like image 156
Leonti Avatar answered Dec 07 '25 06:12

Leonti



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!