Joel Dong-Joe Suh
Joel Dong-Joe Suh

Reputation: 47

Is there an OR statement for jQuery? Not looking for AND statement

I have tried using multiple selectors as shown below but that is unusable in my case. Or is the only way to do it is the long and tedious way, typing each one individually?

$(document).ready(function(){
$("#name,#DOB,#email,#nirc,#mobileno,#haddrs").blur(function(){
    if (!$.trim($("#name,#DOB,#email,#nirc,#mobileno,#haddrs").val())){
    $(this).addClass("error");
    } else {
        $(this).removeClass("error");
    }
});
});

Upvotes: 0

Views: 34

Answers (2)

fdomn-m
fdomn-m

Reputation: 28611

Depending on your requirement, you can use this to indicate the current input and highlight just that input, or you can use .filter to find all of them that are empty.

You can also use .toggleClass with a boolean overload, which is the equivalent of your if/else.

Use this for just the current input:

$("#name,#DOB,#email,#nirc,#mobileno,#haddrs").blur(function(){
   $(this).toggleClass("error", !$.trim($(this).val()))
});
.error { background-color: pink; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id='name'>
<input id='DOB' value='today'>
<input id='email'>

Use .filter to find all empty inputs. I've added ids=".." for reuse.

var ids = "#name,#DOB,#email,#nirc,#mobileno,#haddrs"
$(ids).blur(function() {
  $(ids)
    .removeClass("error")
    .filter(function() {
      $(this).toggleClass("error", !$.trim($(this).val()))
    })
});
.error {
  background-color: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id='name'>
<input id='DOB' value='today'>
<input id='email'>

Upvotes: 1

Adrian
Adrian

Reputation: 8597

You could set up an array of these classes and join them using comma as a delimeter:

var classes = ["#name","#DOB","#email","#nirc","#mobileno","#haddrs"];
var selector = classes.join(', ');

$(selector).blur(function(){...

Upvotes: 0

Related Questions