Помогите с обработкой
Имеется форма:
<input type="text" value="1" size="2" oninput="recalc(2);" name="2"/> И скрипт:
function recalc(product_id) {
var quantity = $('input[name=\'' + product_id + '\']').val();
var quantity = typeof(quantity) != 'undefined' ? quantity : 1;
var options_price = 0;
$('#option_'+product_id+' option:selected, #option_'+product_id+' input:checked').each(function() {
if ($(this).attr('price_prefix') == '+') { options_price = options_price + Number($(this).attr('price')); }
if ($(this).attr('price_prefix') == '-') { options_price = options_price - Number($(this).attr('price')); }
});
var price_no_format = Number($('.change-price'+product_id).attr('price'));
var special_no_format = Number($('.change-special'+product_id).attr('price'));
var new_price = (price_no_format + options_price) * quantity;
var new_special = (special_no_format + options_price) * quantity;
$('.change-price' + product_id).html(price_format(new_price));
$('.change-special' + product_id).html(price_format(new_special));
}
Как добавить ограничение на минимальное и максимальное число ввода в input? Делал следующим образом
function recalc(product_id) {
var quantity = $('input[name=\'' + product_id + '\']').val(nquantity);
var nquantity = +$('input[name=\'' + product_id + '\']').val().value.replace(/\D/g,'')||0;
if (value>maximum) value=maximum;
if (value<minimum) value=minimum;
var quantity = typeof(quantity) != 'undefined' ? quantity : 1;
var options_price = 0;
$('#option_'+product_id+' option:selected, #option_'+product_id+' input:checked').each(function() {
if ($(this).attr('price_prefix') == '+') { options_price = options_price + Number($(this).attr('price')); }
if ($(this).attr('price_prefix') == '-') { options_price = options_price - Number($(this).attr('price')); }
});
var price_no_format = Number($('.change-price'+product_id).attr('price'));
var special_no_format = Number($('.change-special'+product_id).attr('price'));
var new_price = (price_no_format + options_price) * quantity;
var new_special = (special_no_format + options_price) * quantity;
$('.change-price' + product_id).html(price_format(new_price));
$('.change-special' + product_id).html(price_format(new_special));
}
Не получилось. Подскажитеак выполнить такую обработку? |
Цитата:
Цитата:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv='Content-Type' content='text/html; charset=windows-1251' />
<script src='http://code.jquery.com/jquery-latest.js'></script>
<!--
<script src="https://code.angularjs.org/1.3.9/angular.min.js"></script>
<script src="https://code.angularjs.org/1.3.9/angular-route.js"></script>
-->
<style type='text/css'>
</style>
<script type='text/javascript'>
var max=100;
var min=50;
function recalc(product_id) {
var quantity = $('input[name="' + product_id + '"]').val();
var quantity = quantity || 1;
quantity=parseInt(quantity);
quantity=(quantity>max)? max: quantity;
quantity=(quantity<min)? min: quantity;
alert(quantity);
}
</script>
</head>
<body>
<input type="text" value="1" size="2" oninput="recalc(2);" name="2"/>
</body>
</html>
|
При заданных:
var max=100; var min=50; Прекрасно работает, а вот когда через вывод с бд не хочет. Может не правильно вывожу. Хотя вот в этом коде срабатывает:
function quantity(product_id, quantity ,minimum, maximum) {
if (qnty == '') return;
var qnty = Number($('input[name=\'' + product_id + '\']').val());
qnty += Number(quantity);
if(qnty > minimum) {
$('input[name=\'' + product_id + '\']').val(qnty);
recalc(product_id)
} else {
$('input[name=\'' + product_id + '\']').val(minimum);
recalc(product_id)
};
var maxqnty = Number($('input[name=\'' + product_id + '\']').val());
maxqnty == Number(quantity);
if(maxqnty < maximum) {
$('input[name=\'' + product_id + '\']').val(maxqnty);
recalc(product_id)
} else {
$('input[name=\'' + product_id + '\']').val(maximum);
recalc(product_id)
};
}
|
С заданными
var max=100; var min=50; работает прекрасно, а вот если их задавать выводом из бд не работает. А вот в этом скрипте срабатывает:
function quantity(product_id, quantity ,minimum, maximum) {
if (qnty == '') return;
var qnty = Number($('input[name=\'' + product_id + '\']').val());
qnty += Number(quantity);
if(qnty > minimum) {
$('input[name=\'' + product_id + '\']').val(qnty);
recalc(product_id)
} else {
$('input[name=\'' + product_id + '\']').val(minimum);
recalc(product_id)
};
var maxqnty = Number($('input[name=\'' + product_id + '\']').val());
maxqnty == Number(quantity);
if(maxqnty < maximum) {
$('input[name=\'' + product_id + '\']').val(maxqnty);
recalc(product_id)
} else {
$('input[name=\'' + product_id + '\']').val(maximum);
recalc(product_id)
};
}
А в последовательности не хочет максимум цеплять:
function quantity(product_id, quantity ,minimum, maximum) {
if (qnty == '') return;
var qnty = Number($('input[name=\'' + product_id + '\']').val());
qnty += Number(quantity);
if(qnty > minimum) {
$('input[name=\'' + product_id + '\']').val(qnty);
recalc(product_id)
} else {
$('input[name=\'' + product_id + '\']').val(minimum);
recalc(product_id)
};
var maxqnty = Number($('input[name=\'' + product_id + '\']').val());
maxqnty == Number(quantity);
if(maxqnty < maximum) {
$('input[name=\'' + product_id + '\']').val(maxqnty);
recalc(product_id)
} else {
$('input[name=\'' + product_id + '\']').val(maximum);
recalc(product_id)
};
}
function recalc(product_id) {
var quantity = $('input[name=\'' + product_id + '\']').val();
var maximum = $('input[name=\'' + product_id + '\']').val(maximum);
var minimum = minimum;
var quantity = quantity ||1;
quantity=parseInt(quantity);
quantity=(quantity>maximum) ? maximum: quantity;
quantity=(quantity<minimum) ? minimum: quantity;
var quantity = typeof(quantity) != 'undefined' ? quantity : 1;
var options_price = 0;
$('#option_'+product_id+' option:selected, #option_'+product_id+' input:checked').each(function() {
if ($(this).attr('price_prefix') == '+') { options_price = options_price + Number($(this).attr('price')); }
if ($(this).attr('price_prefix') == '-') { options_price = options_price - Number($(this).attr('price')); }
});
var price_no_format = Number($('.change-price'+product_id).attr('price'));
var special_no_format = Number($('.change-special'+product_id).attr('price'));
var new_price = (price_no_format + options_price) * quantity;
var new_special = (special_no_format + options_price) * quantity;
$('.change-price' + product_id).html(price_format(new_price));
$('.change-special' + product_id).html(price_format(new_special));
}
Не работает. Подозреваю, что выводится не то значение в максимум. |
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="ie=edge, chrome=1">
<meta name="viewport" content="user-scalable=no, initial-scale=1, maximum-scale=1, minimum-scale=1, width=device-width, height=device-height, target-densitydpi=device-dpi, minimal-ui">
<style>
[data-product-id] {
display: block;
transform: translate(calc(50vw - 50%), calc(50vh - 50%));
margin: .7em;
border: 0;
}
[data-product-id]:not([type=range]) {
box-shadow: 0 0 1.25vmin gray inset;
padding: .5em;
}
[data-product-id]:invalid {
background: #f88;
}
</style>
</head>
<body>
<!-- Используйте подходящие элементы, здесь вводится число, поэтому я использую input[type=number] -->
<input type="number" min="0" max="50" value="1" data-product-id="2" pattern="\d|[1-4]\d|50">
<input type="number" min="0" max="50" value="1" data-product-id="3" pattern="\d|[1-4]\d|50">
<!-- Для диапазонов также подойдёт input[type=range] -->
<input type="range" min="0" max="50" value="1" data-product-id="1">
<input type="range" min="0" max="50" value="1" data-product-id="0">
<script>
document.addEventListener("input", function(event) {
if(!event.target.hasAttribute("data-product-id")) return;
event.preventDefault();
var input = event.target;
// "Втискиваем" число в заданный диапазон если вне
var value = input.value;
value = isFinite(value) ? value : input.min; // сбросим в минимум, если не число
value = Math.max(input.min, Math.min(input.value, input.max));
// Заменяем на "втиснутое", если отличается от исходного
if(value != input.value)
input.value = value;
// Число value готово
// Вы можете здесь вызвать свою функцию с этим числом,
// я для примера закрашу {{значение}}% от ширины окна
var color = ["black", "purple", "teal", "orange"][input.getAttribute("data-product-id")];
document.body.style.background = "linear-gradient(90deg, " + color + " " + value + "%, transparent 0)";
});
</script>
</body>
</html>
|
Malleys,
Спасибо, но немного не то. Вы осуществляете через - input type="number", а необходимо input type="text". Делается для ocstore |
Да, поскольку если требуется ввести число, то как-то странно использовать input[type=text], на устройствах с сенсорным экраном всплывает клавиатура для ввода текста, а не числа, и это неудобно. На ПК щёлкнув по input[type=number] пользователь сможет менять значение числа прокруткой колеса мыши или стрелками на клавиатуре. A11Y улучает.
|
Через input[type=number] удобней и проще все можно вывести через переменные php. А с input[type=text] проблема не подхватывается количество из базы.
|
Подскажите как передать переменную из
<input name="24" oninput="recalc(24);" size="2" value="1" maximum="13" onblur="isright(this);" type="text">параметр махimum? в php maximum выводится так maximum="<?php echo $product['quantity']; ?>" |
Почему то не выводится количество из базы mysql в отдельный файл *.js, а вот когда скрип добавляешь не отдельным файлом.
То для всех записей в таблице maximum="<?php echo $product['quantity']; ?>" Принимается значение последний записи в таблице товаров. Как увязать maximum="<?php echo $product['quantity']; ?>"с id товара? |
| Часовой пояс GMT +3, время: 05:12. |