Good day. Maybe someone knows how to make automatic rounding of the entered values in the input with the message that the value is changed. This function is necessary to change the number of items in the basket so that there is not any number that the user enters, but a multiple of the number of items in the package. Who knows, tell me, please!)
3 answers
Solution with jQuery. I can write without it.
<input type="text" pack="4" /> <script type="text/javascript"> $('input[pack]').change(function(){ // вешаем обработчик на все инпуты с атрибутом pack var val = ~~this.value || 0; // получаем значение var pack = ~~this.getAttribute('pack') || 0; // получаем кол-во в упаковке if(val%pack != 0){ this.value = val - val%pack; // уменьшаем кол-во // или увеличиваем - this.value = Math.ceil(val/pack)*pack; alert('Значение изменено кратно кол-ву в упаковке!'); } }); </script>
Updated code
Now the script works like this: set the attribute pack in the package - the quantity in the package and ... everything. =) And it works.
Additive
If compatibility with another library is needed, you can also add var j = jQuery.noConflict();
and use j (...) instead of $ (...) or write jQuery (...) instead of $ (...) immediately.
- Ling came and spoiled everything: now he will collect all the pluses and leave%). Listen what is ~~? - knes
- And further. Better to increase the number than to reduce. If my device eats 3 batteries, it does not make sense for me to offer two. - knes
- ~~ - twice bitwise inversion. It can be used instead of parseInt, as it works faster. The only difference is that it does not return NaN, so you have to do || 0 ; ATP, schA I will add. =) - ling
- The user enters the quantity, leaves the inputa - and then the quantity changes and a window pops out with an insult.
var val = ~~this.value || 0;
- it's just getting the value of the input and casting it to an integer. And then there are individuals who write numbers in letters. - ling - it quotes shields slash. They are here apparently replaced with errors issued when I immediately after the input wanted to insert. suffered after the creation of all inputs and no errors - SnowMan
|
<html> <script> function pri() { var t=10; if (t%2 != 1){ alert('тест'); } } </script> <form action=# method=post> <input type="text" onchange="pri();"> </form> </html>
|
var quantity_per_pack = 5; //Число продуктов в упаковке var amount = Math.ceil($('input#user_amount').val()/quantity_per_pack)*quantity_per_pack; $('input#user_amount').val(amount); alert('Значение изменено, чтобы соответствовать целому числу упаковок.');
- var quantity_per_pack = 5; // The number of products in the package is determined by the variable. each product has its own value, different quantity in the package. - SnowMan
- Instead of five, substitute the desired amount. You can substitute dynamically by cramming this text into .change () - knes
|