开发者

JQuery UI Autocomplete: how to strip tags from label before inserting into the input field?

I'm using JQuery UI Autocomplete, I have the set of items returned via ajax with the terms highlighted by the search engine (so the label already contains the html). The problem is that every time I choose an item the value with html tags is inserted into the t开发者_如何学Pythonext box which is of course not nice. I wonder if there is anyway I can strip all tags from the label before inserting into the text box

        var cache = {}, lastXhr;
        $('#location_name').autocomplete({
        source: function( request, response ) {                 

            var q = request.term;
            if ( q in cache ) {
                response( cache[ q ] );
                return;
            }

            lastXhr = $.getJSON( "location_search/", {q: q}, function( data, status, xhr ) {
                $.each(data, function(i, v){
                    data[i].label = v.name + (v.address !== null ? ', ' + v.address : '');
                });

                cache[ q ] = data;

                if ( xhr === lastXhr ) {                                        
                    response( cache [q] );
                }
            });
        },      
        select: function( event, ui ) {
            $('#location_id').val(ui.item.id);
            $('#selected_location').html(ui.item.label);                        
        }
    }).data( "autocomplete" )._renderItem = function( ul, item ) {
        return $( "<li></li>" )
        .data( "item.autocomplete", item )
        .append( "<a>"+ item.label + "</a>" ) //  + + "<br>" + item.desc + "</a>"
        .appendTo( ul );
    };


Add this function:

function stripHTML(oldString) {
  return oldString.replace(/<&#91;^>&#93;*>/g, "");
}

And add to your code:

$('#location_name').change(function(){
    $(this).val(stripHTML($(this).val());
});


In order to make this work you should also pass item.value

On select it looks for item.value first and then for item.label

That way you can leave your select: like that

select: function( event, ui ) {
        $('#selected_location').html(ui.item.label);                        
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜