Xibition Xibition - 3 months ago 13
PHP Question

zerofill checkbox labels and data stored in DB

I already posted a question here and got help with it, but I forgot to mention a little detail ... I now have the results as MA1, MA2.... I want them to be MA0001, MA0002 ... for both checkboxes labels, and the data stored in DB.

my php :

<?php
for ($i = 1; $i < 102; $i++):

echo '<div class="each_checkboxes">';

echo '<label class="contact" for="checkbox'.$i.'"></label>';
echo '<input type="checkbox" name="tape[]" id="checkbox'.$i.'" value=""/>';

echo '</div>';

endfor;
?>


the js :

$(document).ready(function () {
$('#method').change(function () {
var method = $('option:selected').val(),
text = "";

if (method == "CSBSFSR20003") {
text = "MA";
} else if (method == "CSBSAPP20029") {
text = "SAS";
}

$('.contact').each(function (i) {
var value = text + (++i);
$(this).text(value);
$('#' + $(this).attr('for')).val(value);
});
});
});

Answer

Try this one (with a couple of different algorithms for padding the number:

PHP:

<?php
    function addZeros($num){
        if (strlen($num)==3 ){
            $num = '0' . $num;
        }elseif (strlen($num)==2{
            $num = '00' . $num;
        }elseif (strlen($num)==1{
            $num = '000' . $num;
        }
        return $num;
    }
    for ($i = 1; $i < 102; $i++):
        $num = addZeros($i);
        echo '<div class="each_checkboxes">';

        echo '<label class="contact" for="checkbox'.$num.'"></label>';
        echo '<input type="checkbox" name="tape[]" id="checkbox'.$num.'" value=""/>';

        echo '</div>';

    endfor;
?>

javascript:

$(document).ready(function () {
    $('#method').change(function () {
        var method = $('option:selected').val(),
            text = "";

        if (method == "CSBSFSR20003") {
            text = "MA";
        } else if (method == "CSBSAPP20029") {
            text = "SAS";
        }

        $('.contact').each(function (i) {
            var num = addZeros(++i);
            var value = text + num;
            $(this).text(value);
            $('#' + $(this).attr('for')).val(value);
        });
    }); //END #method.change
}); //END document.ready

function addZeros(num) {
  if (num<=9999) { num = ("000"+num).slice(-4); }
  return num;
}

References:

http://stackoverflow.com/a/10073761/1447509

http://php.net/manual/en/function.strlen.php