Reputation: 181
I have form consists of 3 input fields and corresponding span classes beside them. I'm creating a validation with only using jquery/javascript no plugins. Is there a way where the span messages will appear if the user input invalid type of name, like if user input 123 on userName field the span that has message Invalid Username will appear? by only using classes not id's
<input type = 'text' class = 'inputs' id = 'userName'> <span class = 'messageSpan' id = 'userNameMessage'>Invalid Username</span><br><br>
<input type = 'text' class = 'inputs' id = 'phoneNumber'> <span class = 'messageSpan' id = 'phoneNumberMessage'> Invalid Phone Number </span><br><br>
<input type = 'text' class = 'inputs' id = 'emailAddress'><span class = 'messageSpan' id = 'emailAddressMessage'> Invalid Email</span><br><br>"
Here is my code
$(".messageSpan").hide();
$(".inputs")click(function(){
$(this).find('.messageSpan').show();
});
I have tried ung .each but it only shows all the spanMessages once I clicked one field, I want something to make the spanMessage appear only by clicking the corresponding textfield.
Upvotes: 1
Views: 134
Reputation: 3574
$('.messageSpan').hide();
$('.inputs').click(function(){
$(this).next('.messageSpan').show();
});
find
searches all descendants. input
is an empty node (no children). Your spans are siblings of the inputs, not children. next
will select the immediate sibling to the right of the element.
See jQuery next.
Here's an alternative solution which requires changing your HTML.
Setup containers for each input, span pair.
<div class='validate'>
<input type='text' /><span>Invalid Username</span>
</div>
<div class='validate'>
<input type='text' /><span>Invalid Phone Number</span>
</div>
<div class='validate'>
<input type='text' /><span>Invalid Email</span>
</div>
Then:
$('div.validate > span').hide();
$('div.validate > input').click(function(){
$(this).siblings('span').show();
});
Upvotes: 4