0

'Ello StackOverflowers.

So this is my scenario: I populate a ListView using localStorage. Everything working populating that listview and "refreshing" it. BUT!

Now I want to add a search bar if more than 5 elements are added to the ListView. This is my current code (which is not working):

if (resultLength > 5)
{
    // alert('5 or more elemnts found.');
    $("#ConnectionList").attr("data-filter", true);
    $("#ConnectionList").attr("data-filter-placeholder", "Search...");
}

When I uncomment the alert, it fires correctly. Adding .listview('refresh') behind the two lines does not seem to work either.

What am I doing wrong?

Thank you in advance.

Roel
  • 754
  • 3
  • 13
  • 30

1 Answers1

1

Unfortunately this is not going to work. jQuery Mobile will fail to dynamically add filter to an existing listview.

But there's a workaround. Before you populate your listview count number of elements you are trying to populate, if number is 5 or more remove current listview and append new one at the same place. This is another strange thing, if you create a listview from scratch (with filter in mind), filter is going to be successfully generated.

I made an example for you: http://jsfiddle.net/Gajotres/SS7vJ/

$(document).on('pagebeforeshow', '#index', function(){       
    $('<ul>').attr({'id':'test-listview','data-role':'listview', 'data-filter':'true','data-filter-placeholder':'Search...'}).appendTo('#index [data-role="content"]');
    $('<li>').append('<a href="#">Audi</a>').appendTo('#test-listview');
    $('<li>').append('<a href="#">Mercedes</a>').appendTo('#test-listview');
    $('<li>').append('<a href="#">Opel</a>').appendTo('#test-listview');
    $('#test-listview').listview().listview('refresh');
});

Also don't forget to call .listview( twice, first without refresh parameter, and second time with a refresh parameter. Without it you will receive this error:

cannot call methods on listview prior to initialization

You can find more about this problem in this ARTICLE, to be transparent it is my personal blog. Or find it HERE. Look for the chapter called: Markup enhancement problems.

Community
  • 1
  • 1
Gajotres
  • 57,309
  • 16
  • 102
  • 130
  • Perfect. Thanks. Did it slightly different but the same approach (creating the ListView using jQuery instead of creating it in the HTML). – Roel Mar 01 '13 at 21:20