Numeral formatting for currency inside text entry box | XM Community
Skip to main content

I’m new to custom code and have been reading posts about how to automatically add commas and decimals for currency questions in a text entry box or within form field type questions with text entry.

I’ve read up on Cleave.js and have tried code in these posts and have not been able to figure out:

I have a simple question on annual budget with one text entry option. I want respondents to automatically see commas as they type in numbers, and only be allowed to enter up to two decimal points. Ideally, I’d also be able to keep the placeholder currency sign in the box itself as they’re typing in the number, but I know that’s a lot to ask.

Any help would be greatly appreciated.

Hi @Anahivette 
Please try the below code in your text entry question (I have added ‘$’ as the currency sign, you can replace it according to your requirement).

 

Qualtrics.SurveyEngine.addOnload(function() {
    /*Place your JavaScript here to run when the page loads*/
});

Qualtrics.SurveyEngine.addOnReady(function() {
    // Add your input box class or ID
    var inputBox = jQuery(".InputText"); // Replace with your actual class or ID

    inputBox.on("cut copy paste", function (e) {
        e.preventDefault();
    });

    inputBox.on('input', function () {
        // Remove non-numeric characters except for periods (.)
        var sanitizedValue = this.value.replace(/z^0-9.]/g, '');

        // Limit to two decimal places
        var decimalIndex = sanitizedValue.indexOf('.');
        if (decimalIndex !== -1) {
            sanitizedValue = sanitizedValue.substr(0, decimalIndex + 3);
        }

        // Format the number with commas and add $ sign
        this.value = "$" + addCommas(sanitizedValue);
    });

    function addCommas(value) {
        return value.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
    }

    /*Place your JavaScript here to run when the page is fully displayed*/
});

Qualtrics.SurveyEngine.addOnUnload(function() {
    /*Place your JavaScript here to run when the page is unloaded*/
});


@omkarkewat Thank you!! That worked!

I’m assuming the “addCommas” works for all currency that follows this convention in thousands but not in lakhs. Is there a code for inserting commas in the Indian lakh style?

 


Leave a Reply