Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 838
Ranadheer Reddy Avatar asked Jul 24 '26 01:07

Ranadheer Reddy


2 Answers

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();
like image 130
Praveen Kumar Purushothaman Avatar answered Jul 25 '26 15:07

Praveen Kumar Purushothaman


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
like image 21
Denys Séguret Avatar answered Jul 25 '26 14:07

Denys Séguret



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!