axel584 axel584 - 3 months ago 13
jQuery Question

How can I remove a element when another appear?

I use MaterializeCSS to display an email form and when the email validation failed, I would like to hide a "clue" element.



.input-field .clue {
color: #666;
font-family: 'Nothing You Could Do', cursive;
margin-top:-0.8rem;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.14.0/jquery.validate.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.1/css/materialize.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.1/js/materialize.min.js"></script>

<form id="testForm">
<div class="input-field">
<input id="email" type="email" class="validate" required="" aria-required="true">
<label for="email" data-error="wrong email adress" data-success="right">Email</label>
<p id="clue-email" class="clue">We don't spam, never !</p>
</div>
</form>





If you try to input "test" as email adress, the warning message and the clue message are mixed. I would like to hide the clue message ("We don't spam, never !") when the warning message appear ("wrong email adress")

I don't know if I should do this in pure CSS or in Jquery.

Thank you for your help,

Regards,

Axel

Answer

Since input gets invalid or valid class, you can add the following CSS rule, which hides all items having hide-on-input-message class which are located after input in the same input-field:

.input-field input.invalid ~ .hide-on-input-message, 
.input-field input.valid ~ .hide-on-input-message 
{
    display: none;
}

Updated snippet:

.input-field .clue {
	color: #666;
	font-family: 'Nothing You Could Do', cursive;
	margin-top:-0.8rem;
}

.input-field input.invalid ~ .hide-on-input-message, .input-field input.valid ~ .hide-on-input-message {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/jquery.validation/1.14.0/jquery.validate.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.1/css/materialize.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/materialize/0.97.1/js/materialize.min.js"></script>

<form id="testForm">
<div class="input-field">
<input id="email" type="email" class="validate" required="" aria-required="true">
<label for="email" data-error="wrong email adress" data-success="right">Email</label>
<p id="clue-email" class="clue hide-on-input-message">We don't spam, never !</p>
</div>
</form>

Comments