I have script working that will change the value of my textbox as needed. I am trying to change it even more.

var total = 0; // adds a decimal and 2 zeros
$('input:checkbox:checked').each(function(){
 total += isNaN(parseInt($(this).val())) ? 0 : parseInt($(this).val());
}); 

$("#total").val(total.toFixed(2));
$.fn.digits = function(){ // adds a comma every 3 numbers 
    return this.each(function(){ 
        $(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") ); 
    })
}
$("#total").digits();
<input type="text" class="form-control" id="total" style="background-color:#ffffff;">
<span id="total_text"></span>
$("#total_text").digits(); // this works to change the span tag

.toFixed(2) changes the textbox and the span tag just fine.

When I try to add .digits() nothing happens to the textbox.

1 Answers

0
Barmar On Best Solutions

You need to use .val() to read and change the value of a textbox, not .text(). So the function needs to check which type of element $(this) is.

$.fn.digits = function(){ // adds a comma every 3 numbers 
    return this.each(function(){
        var method = $(this).is(":input") ? "val" : "text";
        $(this)[method]( $(this)[method]().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") ); 
    })
}
$("#total").digits();