Jump to content
  • Sign Up
  • 0

увеличение и уменьшение значения type number


cozy_eternity

Question

Здравствуйте, у меня такая проблема, есть код, который увеличивает и уменьшает значение в input при нажатии определённой кнопки, вот только столкнулся с проблемой, если на уменьшение кнопка работает корректно, то кнопка, которая должна увеличивать, при нажатии просто делает значение максимальным. Не могу найти, где я ошибся, прошу помощи.. 

document.addEventListener('DOMContentLoaded', function () {

    if (document.querySelector('.number__but')) {


        let arrNuberCalc = document.querySelectorAll('.number__but');

        for(let i = 0; i < arrNuberCalc.length; i++) {
            mycalc(arrNuberCalc[i]);
        }

        function mycalc(nuberCalc) {
            let numberDown = nuberCalc.querySelector('.number__down'),
                numberUp = nuberCalc.querySelector('.number__up'),
                numberInp = nuberCalc.querySelector('[type="number"]'),
                min = numberInp.getAttribute('min'),
                max = numberInp.getAttribute('max'),
                step = numberInp.getAttribute('step');

            numberDown.addEventListener('click', function (e) {

                e = e || event;
                e.preventDefault();

                numberInp.focus();

                valueInp = numberInp.value || 0;

                if (!(min >= valueInp - step)) {
                    numberInp.value = (valueInp - step);
                } else {
                    numberInp.value = min;
                }
            })

            numberUp.addEventListener('click', function (e) {

                e = e || event;
                e.preventDefault();

                numberInp.focus();

                valueInp = numberInp.value || 0;

                if (!(max <= valueInp + step)) {
                    numberInp.value = (valueInp * 10 + step * 10) / 10;
                } else {
                    numberInp.value = max;
                }
            })
        }
    }
})

 

Link to post
Share on other sites

2 answers to this question

Recommended Posts

  • 0

if (!(max <= valueInp + step))

А почему бы не писать это в виде max > valueInp + step?
Я бы предложил добавить строку debugger внутрь обработчика клика и посмотреть на значения всех переменных

if (!(min >= valueInp - step)) { numberInp.value = (valueInp - step); } else { numberInp.value = min };
А эту штуку можно записать как numberInp.value = Math.max(min, valueInp - step)

Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Answer this question...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • 9 Опрос

    You do not have permission to vote in this poll, or see the poll results. Please sign in or register to vote in this poll.
  • Обсуждения

    • Igor Schnaider
      Ну, если они у вас все в одной колонке, то nth-child(N) можете использовать.
    • Tempest99
      Правильно ли будет сверстать блок из макета так, что блоку с картинкой и блоку с обратной связью нужно будет задавать фиксированную ширину и высоту? Или есть способ более правильный?   Макет https://www.figma.com/file/zwa7oxqCS43WTsPEAQhMik/Форма-заказа?node-id=1%3A40
    • SergeAnt
      Это понятно, но как это сделать? Как выбрать ячейку, в которой есть ссылка? Это возможно в принципе средствами CSS?
    • Katerina23
      С помощью математических функцию удается сделать вращение квадрата состоящий из moveTo и lineTo. Как сделать тоже самое для картинки используя drawImage и transform?  Мне нужно получить вот это пример анимация gif (только с drawImage). Вот пример кода анимации выше (чтобы запустить анимацию нужно удерживать любую кнопку на клавиатуре) <!doctype html> <html> <head> <meta charset="utf-8"> <title>Square 3D</title> </head> <body> <header> </header> <canvas id="canvas" width="400" height="400"></canvas> <script> function Point3d (x, y, z) { this.x = (x === undefined) ? 0 : x; this.y = (y === undefined) ? 0 : y; this.z = (z === undefined) ? 0 : z; this.fl = 250; this.vpX = 0; this.vpY = 0; this.cX = 0; this.cY = 0; this.cZ = 0; } Point3d.prototype.setVanishingPoint = function (vpX, vpY) { this.vpX = vpX; this.vpY = vpY; }; Point3d.prototype.setCenter = function (cX, cY, cZ) { this.cX = cX; this.cY = cY; this.cZ = cZ; }; Point3d.prototype.rotateX = function (angleX) { var cosX = Math.cos(angleX), sinX = Math.sin(angleX), y1 = this.y * cosX - this.z * sinX, z1 = this.z * cosX + this.y * sinX; this.y = y1; this.z = z1; }; Point3d.prototype.rotateY = function (angleY) { var cosY = Math.cos(angleY), sinY = Math.sin(angleY); var x1 = this.x * cosY - this.z * sinY, z1 = this.z * cosY + this.x * sinY; this.x = x1; this.z = z1; }; Point3d.prototype.rotateZ = function (angleZ) { var cosZ = Math.cos(angleZ), sinZ = Math.sin(angleZ), x1 = this.x * cosZ - this.y * sinZ, y1 = this.y * cosZ + this.x * sinZ; this.x = x1; this.y = y1; }; Point3d.prototype.getScreenX = function () { var scale = 0.7415770228276052; return this.vpX + (this.cX + this.x) * scale; }; Point3d.prototype.getScreenY = function () { var scale = 0.7415770228276052; return this.vpY + (this.cY + this.y) * scale; }; window.onload = function () { var canvas=document.getElementById('canvas'), context= canvas.getContext('2d'), BB = canvas.getBoundingClientRect(), points = [], fl = 250, vpX = canvas.width / 2, vpY = canvas.height / 2, angleX, angleY mouse = {x:0,y:0}; var offsetX=BB.left; var offsetY=BB.top; var img = new Image(); img.src="./img1.jpg"; img.width = 150; points[0] = new Point3d(-100, -100, 0); points[1] = new Point3d( 100, -100, 0); points[2] = new Point3d( 100, 100, 0); points[3] = new Point3d(-100, 100, 0); points[0].setVanishingPoint(vpX, vpY); points[1].setVanishingPoint(vpX, vpY); points[2].setVanishingPoint(vpX, vpY); points[3].setVanishingPoint(vpX, vpY); function myMove(e){ e.preventDefault(); e.stopPropagation(); var mx=parseInt(e.clientX-offsetX); var my=parseInt(e.clientY-offsetY); mouse={x:mx,y:my}; } function init() { canvas.onmousemove = myMove; } init(); document.addEventListener("keydown",function(evt) { drawFrame (); }); function drawFrame () { context.clearRect(0, 0, canvas.width, canvas.height); angleX = (392 - vpY) * 0.0005; angleY = (256 - vpX) * 0.0005; points[0].rotateX(angleX); points[0].rotateY(angleY); points[1].rotateX(angleX); points[1].rotateY(angleY); points[2].rotateX(angleX); points[2].rotateY(angleY); points[3].rotateX(angleX); points[3].rotateY(angleY); context.beginPath(); context.fillStyle = "rgba(255,0,0,0.5)"; context.lineTo(points[0].getScreenX(), points[0].getScreenY()); context.lineTo(points[1].getScreenX(), points[1].getScreenY()); context.lineTo(points[2].getScreenX(), points[2].getScreenY()); context.lineTo(points[3].getScreenX(), points[3].getScreenY()); // context.transform(points[0].getScreenX(), points[0].getScreenY(), -points[1].getScreenX(), points[1].getScreenY(), 1,-1); // context.drawImage(img, points[0].getScreenX(), points[0].getScreenY(), 150, 150); context.fill(); context.closePath(); context.stroke(); } }; </script> </body> </html>  
    • Switch74
      если таких страниц у вас не много можно просто прописать для всех Redirect 301 https://site.ru/USLUGI/ https://site.ru/uslugi/ а проще и функциональнее всего сделать проверку на PHP и перенаправлять   $url = urldecode($_SERVER[REQUEST_SCHEME].'://'.$_SERVER[HTTP_HOST].$_SERVER[REQUEST_URI]); $url_ = mb_strtolower($url, 'UTF-8'); if($url_ !== $url) header('Location: '.$url_, true, 301);  
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue. See more about our Guidelines and Privacy Policy