jquery: if ul is empty

2019-01-24 01:04发布

问题:

Okay I have a jQuery dialog box which has a form in it and I am at my wits end trying to figure this out... Lets see if I can verbalize what I am trying to do..

I have 3 text boxes. #apInterest, #apPayment and #apPrincipal in that exact order.

basic english terms of what i am trying to do:

on keyup in #apInterest if .val is less than 0 or greater than 99.99 trigger an error.. else check ul#mylist if it has any li, if not .hide

on keyup in #apPayment if .val is less than 0 trigger an error else check the list for li hide if not.

#apPrincipal is the same thing exactly as #apPayment

what I have right this moment

$('#apInterest').live("keyup", function(e) {
var parent = $('.inter').parents("ul:first");
if ($('#apInterest').val() < 0 || $('#apInterest').val() > 99.99) {
    $('.inter').remove();
    $('#mylist').append('<li class="inter">Interest Rate cannot be below 0 or above 99.99</li>');
    $('#popuperrors').show();
    $(this).addClass('error');
} else {
    $(this).removeClass('error');
    $('.inter').remove();
    alert(parent.children().text);
    if (parent.children().length == 0){
        $('#popuperrors').hide();
    }
}
});

Although I have also tried

if ($("#mylist :not(:contains(li))") ){
$('#popuperrors').hide();
}

I had a function similar to this for all 3 textboxes but none of what I have tried seems to work.. any ideas on how to complete this

回答1:

if ($('#mylist li').length == 0) ...


回答2:

I like using the children() method because it reads nicely and it works even if you've already cached the selector for your ul. Here's what it looks like:

$myList = $('#myList')
if ( $myList.children().length === 0 ) ...


回答3:

jQuery always returns an array of elements. If no matches were found, the array will be empty. An empty array in Javascript evaluates to true:

console.log( !![] ); // logs: true

You want to check the length of the returned set:

if ( ! $("#mylist li").length ){
   $('#popuperrors').hide();
}