Dinh Truong Anh Phuong
Dinh Truong Anh Phuong

Reputation: 137

Show separate number with comma in django tempalte

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

Upvotes: 1

Views: 771

Answers (2)

Ankit Tiwari
Ankit Tiwari

Reputation: 4700

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');
  if(input.value){
    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}}');
  if(input.value){
    input.value = parseInt(input.value).toLocaleString()
  }
}

Upvotes: 2

Vipin Mohan
Vipin Mohan

Reputation: 1631

Two easy ways

1> you can use LOCALIZE to achieve this with limited control

2>You can create a custom django template tag to achieve this using your own logic like split in reverse and insert comma etc.

--EDIT--

from django import template
from django.contrib.humanize.templatetags.humanize import intcomma

register = template.Library()

def currency(dollars):
    dollars = round(float(dollars), 2)
    return "$%s%s" % (intcomma(int(dollars)), ("%0.2f" % dollars)[-3:])

register.filter('currency', currency)

I had previously used this for currency you can modify it as it suits you. in template call {{youvalue|currency}} . Read up on django template tags.

For Javascript:

$('.numberfieldclass').keyup(function() {
  var foo = $(this).val().split(",").join(""); // commas
  if (foo.length > 0) {
    foo = foo.match(new RegExp('.{1,3}', 'g')).join(",");
  }
  $(this).val(foo);
});

Upvotes: 0

Related Questions