Search code examples
javascriptjqueryjavascript-objectscleave

Change the number format in the input text


I want to change the number format with (,) in thousands, for example 2000 to 2,000 20000 to 20,000 and so on. I have tried to browse and I found a suitable library that is cleave.js, but there is one problem in this library which is that I can only recognize one selector, while there are lots of input texts that I want to change, does anyone have another solution?

var cleave = new Cleave('.loan_max_amount', {
    numeral: true,
    numeralThousandsGroupStyle: 'thousand'
});

Solution

  • You can only apply a cleave instance to one element at a time:

    .input-element here is a unique DOM element. If you want to apply Cleave for multiple elements, you need to give different CSS selectors and apply to each of them, effectively, you might want to create individual instance by a loop

    - Cleave Documentation

    Following this advice, you can achieve this by using .querySelectorAll() with .forEach() to loop over all elements with your class and apply a cleave instance to each element like so:

    document.querySelectorAll('.loan_max_amount').forEach(inp => new Cleave(inp, {
      numeral: true,
      numeralThousandsGroupStyle: 'thousand'
    }));
    <script src="https://cdn.jsdelivr.net/npm/cleave.js@1.5.3/dist/cleave.min.js"></script>
    
    <input type="text" class="loan_max_amount" />
    <input type="text" class="loan_max_amount" />