Сравнение входного значения формы JavaScript с максимальным значением ввода - PullRequest
0 голосов
/ 20 сентября 2018

У меня есть <form>, где я пытаюсь сравнить value и max input так, чтобы, если value превышает max, я применил бы другой стиль кввод (как красная граница).Предположим, у меня есть такой ввод:

<input id="inp_1" type="text" numeric-only="" max="50">

И давайте предположим, что у меня есть три входных значения (9, 49 и 59).Я вернусь к этому моменту.

Это мой js-код, который получает данные и проверяет value и max:

var activeInpId = document.activeElement.id;
var activeInpVal = document.activeElement.value;
var activeInpMax = document.activeElement.max;
var pickElement = document.getElementById(activeInpId);
//console 1
console.log("The entered value is (" + activeInpVal + ") and it's max is (" + activeInpMax + ")");

if( activeInpVal > activeInpMax ){
   //console 2
   console.log("Error. Value (" + activeInpVal + ") exceeds max (" + activeInpMax + ")");

   pickElement.style.border = '2px solid';
   pickElement.style.outline = 'none';
   pickElement.style.borderColor = '#E60000';
   pickElement.style.boxShadow = '0 0 10px #E60000';
}else{
   console.log("Current value in range");

   pickElement.style.border = '';
   pickElement.style.outline = '';
   pickElement.style.borderColor = '';
   pickElement.style.boxShadow = '';
}

Проблема

Теперь, когда я ввожу свои входные значения 49 или 59, все работает нормально, но 9 действует как ошибка.Вот скриншот всех 3 сценариев.enter image description here

Кроме того, сообщения консоли в коде выше выводят

The current value in focus is (9) and it's max is (50) для консоли 1 и

Error. Value (9) exceeds max (50) для консоли 2.

Что я мог упустить или сделать неправильно?

Ответы [ 3 ]

0 голосов
/ 20 сентября 2018

просто поместите parseInt в ваше условие if, например

if( parseInt(activeInpVal) > parseInt(activeInpMax) )

, оно работает правильно.

0 голосов
/ 20 сентября 2018

Вам нужно проанализировать строки в целые числа, чтобы иметь возможность сравнивать их, используя >

var inputs = document.querySelector(".input");
inputs.addEventListener("input", validate, false);

function validate(){
  addEventListener("input", function() {
    var activeInpId = document.activeElement.id;
    var activeInpVal = document.activeElement.value;
    var activeInpMax = document.activeElement.max;
    var pickElement = document.getElementById(activeInpId);
    //console 1
    console.log("The entered value is (" + activeInpVal + ") and it's max is (" + activeInpMax + ")");
    console.log(typeof activeInpVal);
    console.log(typeof activeInpMax);
    if (parseInt(activeInpVal) > parseInt(activeInpMax)) {
      //console 2
      console.log("Error. Value (" + activeInpVal + ") exceeds max (" + activeInpMax + ")");

      pickElement.style.border = '2px solid';
      pickElement.style.outline = 'none';
      pickElement.style.borderColor = '#E60000';
      pickElement.style.boxShadow = '0 0 10px #E60000';
    } else {
      console.log("Current value in range");

      pickElement.style.border = '';
      pickElement.style.outline = '';
      pickElement.style.borderColor = '';
      pickElement.style.boxShadow = '';
    }
  });
}
<input class="input" id="inp_1" type="text" numeric-only="" max="50">
<input class="input" id="inp_1" type="text" numeric-only="" max="50">
<input class="input" id="inp_1" type="text" numeric-only="" max="50">
<input class="input" id="inp_1" type="text" numeric-only="" max="50">
<input class="input" id="inp_1" type="text" numeric-only="" max="50">
<input class="input" id="inp_1" type="text" numeric-only="" max="50">
<input class="input" id="inp_1" type="text" numeric-only="" max="50">
0 голосов
/ 20 сентября 2018

Итак, концепция заключается в том, что если мы сделаем

console.log( '9' > '50'); //logs true
console.log( 9 > 50);    //logs false

, то все, что вам нужно сделать, чтобы набрать приведенные значения в целое число перед сравнением.

...