0

In my javascript i am trying to check an array if empty.If there is no item in <li> then array will be empty and this should throw error but it is not working. Here is my code

 var phrases = [];
        $('#listDiv #hiddenItemList').each(function () {
            var phrase = '';
            $(this).find('li').each(function () {
                var current = $(this);
                phrase += $(this).text() + ";";
            });
            phrases.push(phrase);
        });

        if (phrases === undefined || phrases.length == 0 )
        {
            $.alert("Please select rate type, high rate and low rate", {
                title: "Rates Info",
                type: "danger"
            });
            return false;
        }
2
  • just try if(!phrases||!phrases.length) Commented May 12, 2017 at 18:05
  • 1
    There should only be one item that matches #listDiv #hiddenItemList as ID's must be unique so your each function should only execute 1x (kind of necessary) . Also phrases === undefined will always be false as you define phrases = []. Since you always add phrase to phrases even if empty you will always have a count, even if you don't have any li's. Commented May 12, 2017 at 18:08

1 Answer 1

1

You have to check that you're not just pushing an empty string into the array. This will make the array phrases have length and not be undefined but won't be what you're looking for.

    var phrases = [];
            $('#listDiv #hiddenItemList').each(function () {
                var phrase = '';
                $(this).find('li').each(function () {
                    var current = $(this);
                    phrase += $(this).text() + ";";
                });
                if ( phrase != '' ) {
                  phrases.push(phrase);
                }
            });

            if (phrases === undefined || phrases.length == 0 )
            {
                $.alert("Please select rate type, high rate and low rate", {
                    title: "Rates Info",
                    type: "danger"
                });
                return false;
            }
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.