简体   繁体   中英

How i can simplify my if condition in jQuery

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!

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 .

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

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM