Reputation: 175
I have the below code that checks to see if any of my divs has the class "wrong" and if so it shows the jQuery UI dialog box. However i want to extend the code so that it checks those divs and if there are any that are empty it should not show the dialog box.
I've looked around and some people are suggesting using children().length > 0 to accomplish this, but I'm not sure how to write this with my code.
js:
$("#run").click(function() {
if ($("[id^='Drop']").hasClass("wrong")) {
$("#dialog1").dialog("open");
}
});
Upvotes: 4
Views: 213
Reputation: 272106
The following selectors could be used to test if an element is empty or not:
:empty
matches elements that have no children (thus, empty)+:parent
matches elements that have children+Now, rephrasing your statement:
... so that it checks
thosewrong divs and ifthere are any that are emptythey are all full it shouldnotshow the dialog box.
You would write:
var $allWrong = $("id[^='Drop'].wrong"),
$notEmpty = $wrong.filter(":parent");
if ($allWrong.length && $allWrong === $notEmpty) {
// show dialog
}
+ Text nodes are counted when counting children. <span> </span>
contains a text node which contains a whitespace. Therefore it matches :parent
and does not match :empty
.
Upvotes: 4
Reputation: 173562
The logic consists of two parts:
id
property starting with "Drop"
and having the .wrong
class.To do this, I'm saving the first step in an intermediate variable, before doing the final condition:
var $wrongFields = $('[id^="Drop"].wrong');
if ($wrongFields.length && !$wrongFields.filter(':empty').length) {
// at least one field exists with:
// - id starting with "Drop"
// - class of "wrong"
// and none of those fields are empty
$("#dialog1").dialog("open");
}
Upvotes: 2
Reputation: 179
This would also work
$("#run").click(function(){
if ($("[id^='Drop']").hasClass("wrong") && $("[id^='Drop'].wrong:empty").length ) {
$( "#dialog1" ).dialog( "open" );
}
});
Upvotes: 0