1

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.

1 Answer 1

4
$('.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();
});
Sign up to request clarification or add additional context in comments.

1 Comment

Wow dude, srsly, I've been looking for this answer like 2hrs now. Since I don't want to use lots of codes referring by their id's just to show that messageSpan. very well, Thank you! I'll be back to accept the answer .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.