@Zubastik_1

Как добавить разделитель тысяч в виде пробела?

<span class='pups'>100</span>
<span class='pups'>200</span>
<span class='pups'>300</span>
.....

Умножаю их на 10.

$('.pups').each(function() {
this.innerHTML *= 10
})

Вопрос. Как теперь сюда добавить разделитель тысяч в виде пробела?
  • Вопрос задан
  • 5347 просмотров
Решения вопроса 1
Stalker_RED
@Stalker_RED
$('.pups').each(function() {
  this.innerHTML = (parseInt(this.textContent) * 10)
    .toLocaleString('ru-RU')
})
https://jsfiddle.net/s1trghxh/

Или так:
$('.pups').each(function() {
  this.innerHTML = (parseInt(this.textContent) * 10)
    .toString()
    .split('')
    .reverse()
    .map((char, i) => char + (i % 3 ? '' : ' '))
    .reverse()
    .join('')
})
https://jsfiddle.net/12d8cfbq/1

Или регуляркой:
x.toString().replace(/\B(?=(\d{3})+(?!\d))/g, " ");
Ответ написан
Комментировать
Пригласить эксперта
Ответы на вопрос 2
@Ilya33
Еще 1 вариант - работает несколько быстре:
$('.pups').each(function() {
	var ns = (parseInt(this.textContent) * 10).toString();
	var l = ns.length;
	var first = (l % 3 === 0) ? 3 : l % 3;

	var s = ns.substr(0, first);
	for(var i=first; i<l; i+=3) {
            s += ' ' + ns.substr(i, 3);
	}
  
  this.textContent = s;
})

https://jsfiddle.net/4zxr5ccf/
тест производительности: javascript-benchmark.info/ZLN
Ответ написан
Комментировать
ansh
@ansh
IT специалист
Вывод поля Contact Form 7 в Wordpress
<div class="contact-form-field">
        <span class="wpcf7-form-control-wrap text-152"><input type="text" name="text-152" value="" size="40" class="wpcf7-form-control wpcf7-text" aria-invalid="false"></span>
        </div>

Помогите добавить разделитель тысячных в поле "input". Примеры выше не работают. В скриптах "pups" менял на "text-152".

Решил самостоятельно. Возможно кому то пригодится.
1. Добавил script в function.php
function FormatCurrency(ctrl) {
            //Check if arrow keys are pressed - we want to allow navigation around textbox using arrow keys
            if (event.keyCode == 37 || event.keyCode == 38 || event.keyCode == 39 || event.keyCode == 40) {
                return;
            }

            var val = ctrl.value;

            val = val.replace(/ /g, "")
            ctrl.value = "";
            val += '';
            x = val.split('.');
            x1 = x[0];
            x2 = x.length > 1 ? '.' + x[1] : '';

            var rgx = /(\d+)(\d{3})/;

            while (rgx.test(x1)) {
                x1 = x1.replace(rgx, '$1' + ' ' + '$2');
            }

            ctrl.value = x1 + x2;
        }

        function CheckNumeric() {
            return event.keyCode >= 48 && event.keyCode <= 57 || event.keyCode == 46;
        }


<input type="text" onkeypress="return CheckNumeric()" onkeyup="FormatCurrency(this)" />

https://jsfiddle.net/awtszs/rapc69uq/

2. Добавил свой "tag" - "number2" Contact Form 7 в файле .../wp-content/plugins/contact-form-7/modules/text.php
и onkeypress="return CheckNumeric()" onkeyup="FormatCurrency(this)"
Добавлял все строки по аналогии с телефоном ('tel')
и только для "number2" на 55 строке добавил:
if ( in_array( $tag->basetype, array( 'number2' ) ) ) {
			$atts['onkeypress'] = $tag->get_size_option( 'return CheckNumeric()' );
        	$atts['onkeyup'] = $tag->get_size_option( 'FormatCurrency(this)' );
	}
Ответ написан
Комментировать
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы