I have this code to add a class hidden
to a paragraph
But I have 3 input's and doing the same thing for each input
one is a bit awkward, I tried to do it with each
, but I didn't succeed.
The Inputs are the following:
$("#lastname").on('input', function() {
if((($(this).val().length)) > 0) {
$('#error-nombre').addClass('hidden');
}
});
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
<input type="text"class="form-control" id="lastname" name="lastname">
<p class="error-title hidden" id="error-lastname"></p>
</div>
<div class="form-group">
<input type="text"class="form-control" id="name" name="name">
<p class="error-title hidden" id="error-name"></p>
</div>
<div class="form-group">
<input type="text"class="form-control" id="age" name="age">
<p class="error-title hidden" id="error-age"></p>
</div>
I just want to have a function that detects the input
one I am writing and adds the classhidden
For this you can simply look for the sibling element with the class
error-title
, this is achieved with siblings() and then apply thehide()
when the condition is true andshow()
when it is not.In addition, you must eliminate the class
hidden
in each paragraph so that in principle all of them are shown and add the classentrada
with which we will assign the listener. (Ahem, use show and hide , but could have done with addClass and removeClass as well)For that you would need to see which of the inputs is the one that changes, and with
this
, you would apply the property to the specific one, it would look like this:I suppose you have the three inputs inside some div as a container
now with
jquery
, you would use the same thing that you have implemented , but for the container inputs :in this way it would be useful for when it is written in any of the input of the container. Cheers
You can use multiple selector and use closest()
But to your html you have to add the error handler as a class and repeat it
I hope it helps you.