Search code examples
javascriptjquerystringreplacepunbb

Jquery/PunBB Replace Number with String


Using PunBB on Forumotion the idea was to use the Points system to replace the number of points displayed with a string of text. Using a span class I first defined a class 'honorpoints' around the code that shows the number of points a user has.

<span class="honorpoints"><!-- BEGIN profile_field -->{postrow.displayed.profile_field.CONTENT}<!-- END profile_field --></span>

When using that code on the forums it will display a number, based on a user's points, next to their username. The following jQuery code was what I tried to use to replace the number.

$(".honorpoints").each(function(){
    var elm = $(this);
    var number = parseFloat(elm.text(), 10);
    if (number >= 1 && number <= 500) {
        state = "rank 1";
    } else if (number >= 500 && number < 3000) {
        state = "rank 2";
    }
    elm.text(state);
});

However, this doesn't do anything and the numbers are still there. It's supposed to replace UserA : 234 and UserB : 571 with UserA : rank 1 and UserB : rank 2. The code does work however when used on jsFiddle and when working with solely numbers instead of the {postrow.displayed.profile_field.CONTENT} code. Help is appreciated!


Solution

  • Looking at the source of the page you provided in your comment, I believe your $('.honorpoints').each method is being called before the document is fully loaded (99546.js). Unless I'm missing something, you need to wrap that method in a $(document).ready function so it's executed only once the DOM is ready:

    $(document).ready(function() {
        $(".honorpoints").each(function(){
            var elm = $(this);
            var number = parseFloat(elm.text(), 10);
            var state = "";
            if (number >= 1 && number <= 500) {
                state = "rank 1";
            } else if (number >= 500 && number < 3000) {
                state = "rank 2";
            }
            elm.text(state);
        });
    });
    

    I also added a declaration for the state variable since it's a good practice (as it currently is in your question, the state variable is actually window.state because it was not previously declared).