Ranadheer Reddy
Ranadheer Reddy

Reputation: 4324

Reduce multiple if else statements

My Name:<input class="clr" id="name" type="text" /><span class="clr" id="name_error">Name is required</span> <br /><br />

My Email Adress:<input class="clr" id="email" type="text" /><span class="clr" id="email_error">Email is required</span> <br /><br />

My Organisation Name:<input class="clr" id="organisation" type="text" /><span class="clr" id="org_error">Organisation is required</span> <br /><br />

I have 3 input fields. I'm using span to display error message when submitting empty fields.

My problem is, if name field is empty, we should get "Name is required" error, if email field is empty, we should get "email is required" error and so on.

For this, I'm writing below code.

if (name == "")
    $("#name_error").show();
else
    $("#name_error").hide();

if (email == "")
    $("#email_error").show();
else
    $("#email_error").hide();

if (organisation == "")
    $("#org_error").show();
else
    $("#org_error").hide();

Is there any way to reduce if/else statements?

Upvotes: 2

Views: 1138

Answers (2)

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382092

You could do this :

   var obj = window; // or something else, depending on your scope
   ['name', 'email', 'organisation'].forEach(function(v) {
       var $e = $('#'+v+'_error');
       if (obj[v]=="") $e.show();
       else $e.hide();
   });

Note that

  • this supposes a little more strictness, with the replacement of "org" by "organisation"
  • I tried to mimic your code but changing at the root (i.e. where you fill the variables like name) would allow for a simpler code
  • if you know the DOM doesn't change and the error span always follows the input, Praveen's answer is probably simpler and suited

Upvotes: 3

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167162

Using jQuery effectively, you can do this way.

$('input.clr').each(function(){
    if ($(this).val() == "")
        $(this).next('span.clr').show();
});

Before that, we need to hide them this way:

$('span.clr').hide();

Upvotes: 10

Related Questions