Search code examples
javascriptjqueryjquery-mobilejquery-mobile-listviewjquery-mobile-collapsible

Possible to check if a Listview (jQuery Mobile) contains a Collapsible?


I have a random number of collapsibles inside a listview element. What I would like to know is that if there is a way of "knowing" if the listview has any collapsibles in it before proceeding to the next page.

This Fiddle pretty much represents what I have so far.

I would like some sort of client side validation that would check if the "user" has added "medicines" to the list (in a collapsible form) before proceeding.

I've tried playing around with this bit of code:

$("#medListLi").find('div[data-role=collapsible]')....;

But can't seem to know how to properly approach a solution.

Maybe I'm looking at solving this in the wrong way, any suggestions will be very much appreciated.


Solution

  • The selector that you provided just needed .length attached to it like this:

    $("#medListLi").find('div[data-role=collapsible]').length
    

    When using a jQuery selector adding .length to the end always returns the number of matched elements.

    So the above will return 0 if there are no collapsibles 1 if there is one etc...

    To use this in an if statment all you need to do is:

    if ($("#medListLi").find('div[data-role=collapsible]').length > 0) {
        // submit
    } else {
        // error (no collapsibles)
    }