Search code examples
jqueryhtmlformsfieldlive

Checking for input live/with key strokes in HTML input field with jQuery


I need to find a way to hide the span with the ID 'forgot' as soon as the field has any input. The only time the 'forgot' span should be visible is when the field is empty.

<form>
    <input type="text" name="username" placeholder="Username or E-mail" autofocus><br>
    <input type="password" name="password" id='pass' placeholder="Password"><br>
    <span id="forgot">( <a class="forgot" href="<?php echo $dom; ?>forgot/">forgot?</a> )</span>
    <input type="submit" value="Login">
</form>

I currently have this script....

$(document).ready(function() {
    $(document).keypress(function() {
        var value=$.trim($("#pass").val());
        if (value.length==0) {
            $('#forgot').css("display","initial");
        } else {
            $('#forgot').css("display","none");
        }
    }
});

Is there any better way to check for live input from a user and get it to run a function?


Solution

  •  $(document).ready(function() {
        $(document).on('keypress', '#pass', function() {
            var value = $(this).val();
            if (value.length) {
                // $('#forgot').css("display", "block");
                // Or
                $('#forgot').show();
            } else {
                // $('#forgot').css("display", "none");
                // Or
                $('#forgot').hide();
            }
        });
    });
    
    1. You shouldn't be adding event on document, add on pass instead
    2. Use show/hide functions
    3. Use display: block instead of initial
    4. No need to compare to ==0