Reputation: 4324
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
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
name
) would allow for a simpler codeUpvotes: 3
Reputation: 167162
$('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