Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery input number convert Persian/Arabic numbers to English numbers

I have a input field of type number. I want to accept Persian/Arabic numbers as well in this field. I wanted to convert these numbers to English using jQuery, but it seems I can't retrieve these values.

jQuery('input[type="number"]').on('input', function() {
    console.log(jQuery(this).val());
});

For non-English numbers val() is empty string. Is there any way to get the value of a number input field, if the value is not a English number?

UPDATE:

Persian numbers: ۰ ۱ ۲ ۳ ۴ ۵ ۶ ۷ ۸ ۹

English numbers: 0 1 2 3 4 5 6 7 8 9

UPDATE2:

Looks like Firefox returns the correct val but Chrome returns empty string. So my question is applicable on Google Chrome.

like image 631
Pedram Behroozi Avatar asked Feb 09 '16 09:02

Pedram Behroozi


1 Answers

you can use this function:

function toEnglishNumber(strNum) {
        var pn = ["۰", "۱", "۲", "۳", "۴", "۵", "۶", "۷", "۸", "۹"];
        var en = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
        var an = ["٠", "١", "٢", "٣", "٤", "٥", "٦", "٧", "٨", "٩"];
        var cache = strNum;
        for (var i = 0; i < 10; i++) {
            var regex_fa = new RegExp(pn[i], 'g');
            var regex_ar = new RegExp(an[i], 'g');
            cache = cache.replace(regex_fa, en[i]);
            cache = cache.replace(regex_ar, en[i]);
        }
        return cache;
    }
like image 145
MohammadSoori Avatar answered Oct 10 '22 23:10

MohammadSoori