Search code examples
jqueryhtmlonkeydown

input onkeydown event works on first element but not on second


I've got a problem with the onkeydown event. I'm using it on 2 input elements, but it only works on the first. On the second, it just gives me the the error: Uncaught TypeError: object is not a function.
jQuery:

function count() {
    var length = $('#pass').length;
    if (length < 32) {
        $('#length').text(length + ' characters out of 32');
    }
}
function match() {
    if ($('#pass').attr('value') == $('#pass2').attr('value')) 
    {
        $('#match').text('<img src="/css/images/check.png" /> Passwords match.');
    }
    else 
    {
        $('#match').text('<img src="/css/images/close.png" /> Passwords do not match.');
    }
}

HTML:

<form method='post'>
    <input type='password' name='pass' value='' id='pass' onkeydown='count()' />
    <span id='length'></span>
    <input type='password' name='pass2' value='' id='pass2' onkeydown='match()' />
    <span id='match'></span>
</form>

Solution

  • Try the following code block

    <!DOCTYPE html>
    <html lang="en">
        <head>
            <meta charset="utf-8" />
            <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
            <script>
              function count() {
                 var length = $('#pass').val().length;
                 if (length < 32) {
                    $('#length').text(length + ' characters out of 32');
                 }
              }
              function match() {
                 var matchStatus = $('#match').find('span');
                 var matchImg = $('#match').find('img');
                 if ($('#pass').val() == $('#pass2').val()) {
                   matchImg.prop('src', '/css/images/check.png');
                   matchStatus.html('Passwords match');
                 }
                 else {
                    matchImg.prop('src', '/css/images/close.png');
                    matchStatus.html('Passwords do not match');
                 }
              }
    
          </script>
        </head>
        <body>
          <form method='post'>
            <input type='password' name='pass' value='' id='pass' onkeyup='count()' />
            <span id='length'></span>
            <input type='password' name='pass2' value='' id='pass2' onkeyup='match()' />
            <span id='match'>
              <img src="" />
              <span></span>
            </span>
          </form>
        </body>
    </html>
    

    Mistakes I have found

    1. $('#pass').length
    2. onkeydown - should be onkeyup - because first it will fire onkeydown then will place the text (so length and equality will give wrong result)
    3. Make the code simple as possible when you access an item using script. Do not do $('#match').text again and again. Instead assign to one var obj and use it.

    Hope this will help you.. :)