Ввод дробных чисел через input
Такая проблема: есть input типа "text":
<input id="WPVG" type="text" name="workpay">
В него вводятся дробные числа (например, 1.1), но когда я пытаюсь производить применить полученное значение в каком-либо условии, с использованием дробных значений, система выбирает лишь два возможных варианта: 0 и 1, а все остальные дробные варианты просто игнорирует. При этом нет никаких ошибок, из-за чего я не могу понять, что не так.
let WorkPayVG = 0;
WorkPayVG = Number(document.querySelector('[name="workpay"]').value);
if (WorkPayVG == 0) {
document.getElementById('RVG03').style.display = 'inline';
document.getElementById('RVG03').style.color = 'red';
document.getElementById('RVG03').innerHTML = 'Warning! Your people are unhappy that you don\'t pay them! Settle this issue quickly or it may lead to an uprising and loss of people!';
} else if (0 < WorkPayVG <= 0.25) {
document.getElementById('RVG03').style.display = 'inline';
document.getElementById('RVG03').style.color = 'red';
document.getElementById('RVG03').innerHTML = 'Warning! Your people are unhappy that you pay them too little for their work! Please resolve this issue quickly or it may lead to people fleeing!'
} else if (0.25 < WorkPayVG <= 0.5) {
document.getElementById('RVG03').style.display = 'inline';
document.getElementById('RVG03').style.color = 'red';
document.getElementById('RVG03').innerHTML = 'Warning! You pay your people too little! If you don\'t take action, they will begin to starve!';
} else if (0.5 < WorkPayVG <= 0.75) {
document.getElementById('RVG03').style.display = 'inline';
document.getElementById('RVG03').style.color = 'red';
document.getElementById('RVG03').innerHTML = 'Warning! Your people\'s income is barely enough to make ends meet!';
} else if (0.75 < WorkPayVG <= 1) {
document.getElementById('RVG03').style.display = 'inline';
document.getElementById('RVG03').style.color = 'green';
document.getElementById('RVG03').innerHTML = 'Your people are fed and clothed, what else is needed for happiness?'
console.log('WorkPayVG 0.75-1:', WorkPayVG);
} else if (WorkPayVG > 1) {
document.getElementById('RVG03').style.display = 'inline';
document.getElementById('RVG03').style.color = 'green';
document.getElementById('RVG03').innerHTML = 'Your people are happy about your generosity, which translates into increased efficiency at work.';
console.log('WorkPayVG >1:', WorkPayVG);
}
Помогите понять, что не так? Почему система не видит дробных чисел? Подозреваю, что прблема в типе данных, но как указать системе, что нужно учитывать дробную часть, не понимаю.
Ответы (2 шт):
let WorkPayVG = 0;
WorkPayVG = parseFloat(document.querySelector('[name="workpay"]').value);
if (WorkPayVG == 0) {
document.getElementById('RVG03').style.display = 'inline';
document.getElementById('RVG03').style.color = 'red';
document.getElementById('RVG03').innerHTML = 'Warning! Your people are unhappy that you don\'t pay them! Settle this issue quickly or it may lead to an uprising and loss of people!';
} else if (WorkPayVG > 0 && WorkPayVG <= 0.25) {
document.getElementById('RVG03').style.display = 'inline';
document.getElementById('RVG03').style.color = 'red';
document.getElementById('RVG03').innerHTML = 'Warning! Your people are unhappy that you pay them too little for their work! Please resolve this issue quickly or it may lead to people fleeing!';
} else if (WorkPayVG > 0.25 && WorkPayVG <= 0.5) {
document.getElementById('RVG03').style.display = 'inline';
document.getElementById('RVG03').style.color = 'red';
document.getElementById('RVG03').innerHTML = 'Warning! You pay your people too little! If you don\'t take action, they will begin to starve!';
} else if (WorkPayVG > 0.5 && WorkPayVG <= 0.75) {
document.getElementById('RVG03').style.display = 'inline';
document.getElementById('RVG03').style.color = 'red';
document.getElementById('RVG03').innerHTML = 'Warning! Your people\'s income is barely enough to make ends meet!';
} else if (WorkPayVG > 0.75 && WorkPayVG <= 1) {
document.getElementById('RVG03').style.display = 'inline';
document.getElementById('RVG03').style.color = 'green';
document.getElementById('RVG03').innerHTML = 'Your people are fed and clothed, what else is needed for happiness?';
console.log('WorkPayVG 0.75-1:', WorkPayVG);
} else if (WorkPayVG > 1) {
document.getElementById('RVG03').style.display = 'inline';
document.getElementById('RVG03').style.color = 'green';
document.getElementById('RVG03').innerHTML = 'Your people are happy about your generosity, which translates into increased efficiency at work.';
console.log('WorkPayVG > 1:', WorkPayVG);
}
В JavaScript операторы сравнения не поддерживают сравнение диапазонов с использованием двух операторов (< и <=) в одном выражении. Вместо этого вы должны сравнивать каждое значение отдельно.
Я бы предложил вообще отказаться от множественных if-ов, сделав массив с граничными значениями с перебором в цикле. Это и нагляднее и компактнее.
msgs = [[0, 'red', 'Warning! Your people are unhappy that you don\'t pay them! Settle this issue quickly or it may lead to an uprising and loss of people!'],
[0.25, 'red', 'Warning! Your people are unhappy that you don\'t pay them! Settle this issue quickly or it may lead to an uprising and loss of people!'],
[0.5, 'red', 'Warning! You pay your people too little! If you don\'t take action, they will begin to starve!'],
[0.75, 'red', 'Warning! Your people\'s income is barely enough to make ends meet!'],
[1, 'green', 'Your people are fed and clothed, what else is needed for happiness?'],
[Infinity, 'green', 'Your people are happy about your generosity, which translates into increased efficiency at work.']]
let WorkPayVG = prompt('Введите WorkPayVG [0+]: ').replace(',','.');
for (let i = 0; i < msgs.length; i++) {
if (WorkPayVG <= msgs[i][0]) {
console.info(`WorkPayVG задан ${WorkPayVG}, это попадает в ячейку от (${i > 0 ? msgs[i - 1][0] : -Infinity} < ${WorkPayVG} <= ${msgs[i][0]}]`)
console.log(`document.getElementById('RVG03').style.display = 'inline';
document.getElementById('RVG03').style.color = '${msgs[i][1]}';
document.getElementById('RVG03').innerHTML = '${msgs[i][2]}';`)
break;
}
}