Question

I have a system this counts how many textboxes in the class "Today" have the value "/". I want this to also count if it has the value "L" or "l". I have tried the following:

$('.today').keyup(function() {
    var Presents = $('input:visible').filter(function(){
      return this.value == "/";  
    });
    $("#counter").html( "Present: " + Presents.length );
});
$( document ).ready(function() {
    var Presents = $('input:visible').filter(function(){
      return this.value == "/";  
    });
    $("#counter").html( "Present: " + Presents.length );
});

I have tried the following solution:

return this.value == "/", "l", "L";  

This resulted in all of the text boxes being counted, whatever the value.

Was it helpful?

Solution

The shortest answer here is probably regex:

return /^[\/lL]$/.test(this.value);

(This checks for a single-char string where the char is one of /, i, or L.)

More generally, your choices here are essentially:

  • An OR'd series of conditionals: val === "/" || val === "i" || val === "L". This is clear, but redundant, and stops being legible after about three options. It's worth noting, however, that this is probably the fastest option - this might matter if you had to test 10k strings in quick succession.

  • A regex check as above. This is likely the most concise code, and it's easy to add more characters or more complex patterns to the check, but it's less legible.

  • Array inclusion. This is easiest when you have access to modern array methods, e.g. return chars.any(function(c) { return c === val; }). This may be the best option if your list of search strings is determined at runtime, or simply if it's very long.

OTHER TIPS

That's because your code is identical to return "L", which is truthy, so all inputs are returned.

Did you mean:

return this.value == "/" || this.value == "l" || this.value == "L";

If so, you could also use:

return this.value.length == 1 && "/lL".indexOf(this.value)+1;

Might not seem like much of a savings, but allows you to define your list of characters much more easily, in case you want to add more in future.

try: return this.value.match(/[\/li]/) !== null

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top