Home > Blockchain >  Is there an OR statement for jQuery? Not looking for AND statement
Is there an OR statement for jQuery? Not looking for AND statement

Time:12-17

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");
    }
});
});

CodePudding user response:

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(){...

CodePudding user response:

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'>

  • Related