Add 0 in front of 1-9

636 Views Asked by At

I have a div with a number, which changes dynamically in php. The number comes from the slide number in the Supersized plugin. I have tried my best to figure out how to change the plugin, so I could fix it with php, but without any luck.

I would like to "force" this number to always have a 0 in front of it, if it is below 10. So if the number is 5, it should be 05.

I found a solution with jQuery, but it is only working until the next slide loads and the number changes, and then the next number has no zero in front of it. This is the script:

$(".number").text(function(i, val){
    return $.trim(val).length === 1 ? '0' + val : val;
});

Is there a way to make jQuery keep checking the number, and adding a zero every time the number is below 10? Or some other solution?

Hope someone can help :)

3

There are 3 best solutions below

1
user3152069 On

Um would it be okay to do it in php ?

echo addZero(6);

function addZero($n){
  if($n < 10 && $n > -1) return "0".$n;
  else return $n;
}
5
Chad La Guardia On

If you want to use JQuery, you could change the inner element of the div to be a text input and style it to look like text. Then, bind your function to the textfield's change event.

$(".number").change(function(i, val){
    return $.trim(val).length === 1 ? '0' + val : val;
});

This will allow your function to be called any time the text is changed.

[1]Here's a good link to show all the various events you can use in JQuery and [2]the post I linked in the comments regarding monitoring DOM properties.

  1. http://api.jquery.com/category/events/
  2. http://james.padolsey.com/javascript/monitoring-dom-properties/
0
Cody On

Just made this (pretty dirty) hack, and it fixed my problem! I was able to insert <span class="extra-zero">0</span> before <div class="number">

And then hide or show it with this code:

$(".number").bind("DOMSubtreeModified",function(){
    $(function() {
        $(".number").filter(function() {
            if ($(this).text() < 10 ) {
                $('.extra-zero').css({ 'display': 'inline' });
                    }                   

            else {
                $('.extra-zero').css({ 'display': 'none' });
                }                       
        });
    });
}); 

It would have been nicer to prepend the span with the zero, but it didn't work for me, so I think I will stick with my dirty hack. Thank you all for answering and trying to help.