Squishy
Squishy

Reputation: 193

jQuery Mobile: filtering nested lists

I need to be able to implement a filter in my jQuery Mobile project that would allow me to search a nested list and return all list elements that match the text entered into the filter bar. Basically I need to extend the functionality of the already implemented data-filter function to show results from nested list items as well as visible ones. Is there a way to modify the data-filter behaviour?

My list is set up as follows. I need to return a list with each sitesource and datasource (including child elements) that match the search term.

<ul>
<li class="sitesource">
    <ul>
        <li class="datasource"></li>
        <li class="datasource"></li>
        <li class="datasource"></li>
    </ul>
</li>
<li class="sitesource">
    <ul>
        <li class="sitesource">
            <ul>
                <li class="datasource"></li>
                <li class="datasource"></li>
                <li class="datasource"></li>
            </ul>
        </li>
        <li class="datasource"></li>
    </ul>
</li>
<li class="datasource"></li>
</ul>

I suspect that what I may need to do is (after pageinit) search through the entire html document and return all the matching sitesource and datasource elements in a list - this would probably require a custom built function?

Upvotes: 3

Views: 1513

Answers (2)

Ady
Ady

Reputation: 19

I know this post is so old, but right now i meet the same problem and has found the solution

Fortunately with the latest JQM (1.4.5) you can easily add data-children=".datasource" on the parent <ul> attribute

For more info : http://api.jquerymobile.com/filterable/#option-children

Hope my answer can help anyone else who meet the same problem, regards

Upvotes: 0

Andrew Klatzke
Andrew Klatzke

Reputation: 544

This is a little verbose, but seems to do what you're asking:

function filterSources(myVal){
var myFilter = myVal;

var dataSources = document.getElementsByClassName("datasource");

//array from nodelist    
var arr = [];
for(var i = 0, n; n = dataSources[i]; ++i) arr.push(n);

//filter for text    
var finalData = arr.filter(function(element){
        return $(element).text().indexOf(myFilter) > -1;
    })
//compile into string for output
var newStr = "";
for(var m in finalData) newStr += finalData[m].textContent + ", ";
$("#target").html(newStr);


}

$(function(){

filterSources
$("input#search_foo").keyup(function(){
    filterSources($(this).val())
    })
})

http://jsfiddle.net/klatzkaj/DEmWE/9/

Upvotes: 1

Related Questions