2

I'm looking for a way to do the following:

$("#a" || "#b").val() === ""

as opposed to:

$("#a").val() === "" || $("#b").val() === ""

Any ideas?

Thanks in advance!

4
  • 6
    What's wrong with the way you say you don't want to do it? It's clear, concise and above all else works! Commented May 24, 2013 at 8:29
  • 1
    Just thought it could be simplified! :] Commented May 24, 2013 at 8:32
  • +1 your question is interesting.But i dont know is there any solution for this Commented May 24, 2013 at 8:36
  • 1
    In my opinion better suited for codereview.stackexchange.com Commented May 24, 2013 at 8:50

4 Answers 4

3

For two elements, I believe your example is about as short as you can make it and its meaning is clear. However, if you wish to repeat such logic or evaluate more elements, you might be able to improve upon it by creating a simple function to evaluate if any items in a set match a condition.

Extending jQuery

$.fn.any = function (evaluator) {
    var items = $(this);
    for (var i = 0; i < items.length; i++) {
        if (evaluator(items[i]) === true) {
            return true;
        }
    }

    return false;
};

Demo: http://jsfiddle.net/xE76y/1/

This is similar to the Any() method implemented in the .Net LINQ library* (and I'm sure is implemented in other libraries, especially those geared towards functional programming). In c#, you would call such a method:

enumerable.Any( o => o.Value == "" );

JavaScript's syntax (sadly) isn't as concise; you end up with something like:

array.any( function(o){ return o.value === ""; } );

So far, this hasn't saved you anything. However, if you want to iterate over a large number of elements, it becomes much more elegant.

// there could be zero inputs or 100 inputs; it doesn't matter
var result = $("input").any(function (o) {
    return o.value === "";
});

Native Solution

Note that we aren't relying on jQuery in our any() method. You could also consider a native JavaScript solution such as the Array.some() method.

some() executes the callback function once for each element present in the array until it finds one where callback returns a true value. If such an element is found, some immediately returns true.

Demo: http://jsfiddle.net/xE76y/2/

var result = jQuery.makeArray($("input")).some(function (o) {
    return o.value === "";
});

Since this is an array method, it only works on an array. This unfortunately means that document.getElementsByTagName("input").some(...) will not work since getElementsByTagName() returns a NodeList.

Of course, you could push whatever you wanted into an array and call some() on that array. The call to jQuery.makeArray() in the example is just for convenience.

Abstracting the Evaluation Functions

Demo: http://jsfiddle.net/xE76y/3/

Perhaps the evaluation functions (such as testing for an empty string) will be reused. These can be abstracted further.

// ideally, this should NOT be left in global scope
function isEmpty(input) {
    return input.value === "";
}

// the check now fits nicely in one line.
if ($("input").any(isEmpty)) {
    alert("At least one input is empty.");
}

The resulting method calls are quite clean: $("#a, #b").any(isEmpty) and $("input").any(isEmpty)


* Also worth noting that LINQ has been recreated for JavaScript.

Sign up to request clarification or add additional context in comments.

Comments

2

Try like this instead:

 if ($('#a,#b').is(':empty'))
    {
      alert("Either a or b is Empty!");
     }

Try my demo

Edit:

If it is an input type like a textbox then it would be a little bit bulky but will achieve the same effect:

if ($.inArray("",[ $("#a").val(), $("#b").val() ])>=0)
{
    alert("Either a or b is Empty!");   
}

See another Demo

1 Comment

Does that work correctly with inputs? jsfiddle.net/mcnVm/3. This looks like it will always return true for an input, as it cannot contain children: api.jquery.com/empty-selector
0

If you want to avoid duplication of the empty string "", you could do this:

if ($.inArray([ $("#a").val(), $("#b").val() ], ""))

Or if you only want to select once with jQuery:

if ($.inArray($("#a, #b").map(function() { return this.value; }), ""))

But I wouldn't use either of these myself. They are arguably both less efficient, more contrived, and certainly less readable than the "easy" way!

Comments

-1

I'm not an expert in javaScript, but have you cross checked with :

http://api.jquery.com/multiple-selector/

jQuery selector regular expressions

Also, one way would be using the .each function as in

jQuery Multiple ID selectors

1 Comment

@MarcelGwerder thanks for the information. good to know that. Let me quote the jQuery reference now. +1 to you.

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.