Show separate number with comma in django tempalte

Welcome to Programming Tutorial official website. Today - we are going to cover how to solve / find the solution of this error Show separate number with comma in django tempalte on this date .

I have an issue that when the user is typing on text field the number is not separated by a comma

user is typing 500000, it shows 500000 not 500,000

in models

so_tien=models.PositiveIntegerField(max_length=50)

in forms

so_tien=forms.IntegerField(label="Số tiền",widget=forms.NumberInput(attrs={"class":"form-control",'onfocusout': 'numberWithCommas()',}),required=False)

template file

<div class="col-md-4" id="sotien" style="display:none">{{ form.so_tien}}</div>

javascript code numberWithCommas in the template file:

 <script language="JavaScript">
function numberWithCommas(){
  var input = document.getElementById('{{ form.so_tien.id_for_label}}');
  input.value = parseInt(input.value).toLocaleString()

}

Thanks for your reading

Answer

You’re not changing value of your input you’re just displaying it try assign new value to value attribute like this

Working example

function numberWithCommas(){
  var input = document.getElementById('input');
  input.value = parseInt(input.value).toLocaleString()
}
<input type="text" id="input" onfocusout="numberWithCommas()">

for django you can do somthing like this
in forms.py

so_tien=forms.CharField(label="Số tiền",widget=forms.TextInput(attrs={"class":"form-control", 'onfocusout': 'numberWithCommas()',}),required=False)

inside your templates

function numberWithCommas(){
      var input = document.getElementById('{{ form.so_tien.id_for_label}}');
      input.value = parseInt(input.value).toLocaleString()
}