如何使用此 JQuery 更改文本框的值?

How do I change the value of a textbox with this JQuery?

我有脚本可以根据需要更改我的文本框的值。我正在努力改变它。

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, ",") ); 
    })
}
$("#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) 更改文本框和 span 标签就好了。

当我尝试添加 .digits() 时,文本框没有任何反应。

您需要使用 .val() 来读取和更改文本框的值,而不是 .text()。所以该函数需要检查 $(this) 是哪种类型的元素。

$.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, ",") ); 
    })
}
$("#total").digits();