PeMaCN PeMaCN - 5 months ago 12
Javascript Question

Tick and cross after input - jQuery

everybody. I want to display tick next to the input field if the user has written some text (or is still writing) and cross if the input field is empty.
This is my try:

$('#myForm input').blur(function (){
if($(this).val() == '')
{
$(this).after("<img src='./media/img/cross.png' style='margin-top: 15px;'/>");
}
});

$('#myForm input').keypress(function (){
if($(this).val() != '')
{
$(this).after("<img src='./media/img/tick.png' style='margin-top: 10px; width: 1.5em; height: 1.5em;'/>");
}
});


Upper code adds image whenever the user types a letter. How can I avoid this? Is there more elegant way to do this?

Thanks in advance.

UPDATE

This is my HTML:

<form id="myForm" name="loginForm">
<input type="text" class="input" placeholder="Username" id="username"/>
<input type="password" class="input" placeholder="Password" id="password"/>
<input type="submit" class="btns" value="Login" name="submitLogin"/>
</form>

Answer

Add both image tags to the html, and give them a class with display: hidden. Use your events not to add DOM elements with .after(), but use them to set or unset the hidden class on your imgs respectively, kinda like this:

$('#myForm input').blur(function (){
        if($(this).val() == '')
        {
            $(this).next('.tick').addClass('hidden');
            $(this).next('.tick').next('.cross').removeClass('hidden');
        }
    });

    $('#myForm input').keypress(function (){
        if($(this).val() != '')
        {
            $(this).next('.tick').next('.cross').addClass('hidden');
            $(this).next('.tick').removeClass('hidden');
        }
    });
.hidden {display: none}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myForm" name="loginForm">
    <input type="text" class="input" placeholder="Username" id="username"/><img class="hidden tick" src="#" alt="tick" /><img class="hidden cross" src="#" alt="cross" /><br/>
    <input type="password" class="input" placeholder="Password" id="password"/><img class="hidden tick" src="#" alt="tick" /><img class="hidden cross" src="#" alt="cross" /><br/>
    <input type="submit" class="btns" value="Login" name="submitLogin"/>
</form>