Pergunta

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.

Foi útil?

Solução

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)
}

Outras dicas

I think you want a JavaScript condition that will evaluate to true if your #medListLi contains a collapsible element:

if ( $("#medListLi").find('div[data-role=collapsible]').length ) {
    //yup, their is something collapsible in here
}

This code does the following:

  1. select the element with an id of #medListLi within that element,
  2. find any div that has a data-role attribute set to "collapsible"
  3. jQuery returns any such elements in an array; the .length JavaScript property will return a 0 or some positive number, which gets evaluated to false (for 0) or true (for any other positive number).
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top