Miguel Moura
Miguel Moura

Reputation: 39474

Add and Remove html based on condition

I have the following input:

<input type="text" name="country" />

When a variable error is not null I will show the message after it:

<input type="text" name="country" />
<span class="error">Some error message</span>

When the variable error is null I need to remove the message.

So I have the following, being element the input tag:

if (error != null) {
  var message = element.next("span.error");
  if (message == null)
    element.after("<span class='error'>" + error + "</span>");
  else
    error.text(error);
} else {
  element.next("span.error").remove();
}

However, the message is never added when error is not null.

What am I missing? And is there a way to improve my code?

Upvotes: 0

Views: 2758

Answers (2)

TheEllis
TheEllis

Reputation: 1736

Per the comments above, your code should work when revised like this, assuming that element is a jquery object:

if (error != null) {
   var message = element.next("span.error");
   if (message.length == 0)
      element.after("<span class='error'>" + error + "</span>");
   else
      message.text(error);
} else {
   element.next("span.error").remove();
}

Upvotes: 1

TheEllis
TheEllis

Reputation: 1736

An easier way to do this:

if (error !== null) {
    $("span.error").text(error).show();        
} else {
    $("span.error").hide();
}

In the above example, you would start out with the error span element on the page, but have it hidden.

<span class="error" style="display:none"></span>

That being said, I can see at least one thing wrong with your code. In this line

error.text(error);

I believe you meant

message.text(error);

Also, is the element a variable created from a jquery selector? If it's just a reference to a DOM element and not a jquery object then your code won't work.

Upvotes: 1

Related Questions