2

I made a script to count characters from form textfields but is now working. I put an alert inside of keyup function to see if it counts correctly, but every time i is 6 (the total of form elements). Outside of keyup function it counts correctly. What could be the problem? I don't see any problems with the code. Also the console log is empty (no errors).

// Count characters
formElementsTitles = ['content_title', 'content_description', 'text_content', 'image_url', 'video_embed', 'aditional_info'];
formElementsLengths = ['100', '5000', '20000', '1000', '1000', '1000'];

for(i = 0; i < formElementsTitles.length; i++)
{   
    $('#'+formElementsTitles[i]).keyup(function() {

        charactersMax = formElementsLengths[i];
        charactersCurrent = $(this).val().length;
        charactersRemaining = charactersMax - charactersCurrent;

        if(charactersCurrent >= charactersMax)
        {
            $("#count_"+formElementsTitles[i]).html('<span class="content_count_chars_yellow">'+charactersRemaining+'</span> characters remaining');
        }
        else
        {
            $("#count_"+formElementsTitles[i]).html('<span class="content_count_chars_green">'+charactersRemaining+'</span> characters remaining');
        }
    });
}
4

1 回答 1

1

You are trying to use the ivariable in an event function, that won't work since the function will only be executed when the Event really happens !

This should be working for you :

var formElements = {
    content_title: {
        maxLength: 100
    }
}

for(title in formElements)
{   
    $('#'+title).keyup(function() {

        var charactersMax         = formElements[$(this).attr('id')].maxLength;
        var charactersCurrent     = $(this).val().length;
        var charactersRemaining   = charactersMax - charactersCurrent;

        if(charactersCurrent >= charactersMax)
        {
            $("#count_"+$(this).attr('id')).html('<span class="content_count_chars_yellow">'+charactersRemaining+'</span> characters remaining');
        }
        else
        {
           $("#count_"+$(this).attr('id')).html('<span class="content_count_chars_green">'+charactersRemaining+'</span> characters remaining');
        }
    });
}

See fiddle here : http://jsfiddle.net/rA2Fm/

于 2013-03-23T15:09:21.780 回答