.className не работает при проверке формы - PullRequest
1 голос
/ 21 марта 2020

У меня проблема с .className как для getWeight.length <1, так и для getHeight.length <1, из-за отсутствия имени класса formValidation. </p>

Есть идеи, почему это не работает? Я так долго смотрю на код, что не могу понять, что происходит!

Большое спасибо

JS

function calculateBMI() {

  let getWeight = document.getElementById('weight').value;
  let getHeight = document.getElementById('height').value;
  let getBMI = (getWeight / (getHeight*getHeight)).toFixed(2);
  let displayBMI = document.getElementById('displaybmi');

  if (getWeight.length < 1) {
     //alert('Please enter your weight');
      getWeight.className = 'formValidation';
    }
  else if (getHeight.length < 1) {
     //alert('Please enter your height');
     getHeight.className = 'formValidation';
    }
  else if(getBMI < 18.5) {
    displayBMI.className = 'displaybmi green';
    displayBMI.textContent = 'You\'re under weight! ' + getBMI;
    } 

   else if (getBMI >= 18.5 && getBMI <= 25) {
    displayBMI.className = 'displaybmi green';
    displayBMI.textContent = 'You\'re normal weight! ' + getBMI;
    }

   else if (getBMI > 25 && getBMI <= 29.99) {
    displayBMI.className = 'displaybmi yellow';
    displayBMI.textContent = 'You\'re over weight! ' + getBMI;
    }

   else if (getBMI >= 30 && getBMI <= 34.99) {
    displayBMI.className = 'displaybmi orange';
    displayBMI.textContent = 'You\'re obese! ' + getBMI;
    }

   else {
    displayBMI.className = 'displaybmi red';
    displayBMI.textContent = 'You\'re very obese! ' + getBMI;
   } 

}
.displaybmi {
  font-size: 16px;
  padding: 20px;
  margin-bottom:20px;
}

.red{
  background:red;
}

.yellow {
  background: yellow;
}

.green{
  background:green;
}

.orange {
  background:orange;
}

.formValidation {
  border: 2px solid red;
}

1 Ответ

4 голосов
/ 22 марта 2020

Вы пытаетесь добавить имя класса к значению элемента (вход, я полагаю).

getWeight и getHeight являются значениями, а не фактическими элементами DOM.

Попробуйте:

let getWeight = document.getElementById('weight');
let getHeight = document.getElementById('height');
let getBMI = (getWeight.value / (getHeight.value*getHeight.value)).toFixed(2);

if (getWeight.value.length < 1) {
    //alert('Please enter your weight');
    getWeight.className = 'formValidation';
}
else if (getHeight.value.length < 1) {
    //alert('Please enter your height');
    getHeight.className = 'formValidation';
}

CodePen здесь

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...