当我在3和10之间时,它被标记为大于20。

huangapple go评论56阅读模式
英文:

When I go between if I go between 3 and 10, its marked as greater than 20

问题

如果元素Wager设置为大于3且小于10,JavaScript会将其标记为大于20。我原本预期在3和10之间的任何值都会被标记为小于20,但似乎有一些愚蠢的问题。

英文:

If the the element Wager is set to anything above 3 and under 10. Javascript marks it as above 20.

<input type="number" id="wager" step="0.1" min="0.1" max="20.0" placeholder="0.1"/>

function setTwoNumberDecimal(event) {
    this.value = parseFloat(this.value).toFixed(1); 

    console.log(this.value) // Shows the current value (debugging)
    console.log(this.max) // Shows the max value allowed (debugging)
    console.log(this.value > this.max) // Shows if its above the max allowed (debugging)

    if (this.value > this.max) {
        this.value = this.max
    }

    if (this.value < 0.1) {
        this.value = 0.1
    }
}

I was expecting so anything between 3 and 10 would be marked as lower than 20 but yeh. It probably is something stupid.

答案1

得分: 0

这种行为是由比较字符串引起的。首先,this.valuethis.max 从HTML元素中返回字符串,即使在分配了数值后仍然是字符串。其次,toFixed() 方法也返回一个字符串。因此,我们将在比较值之后应用它。

function setTwoNumberDecimal(event) {
  var _thisValue = parseFloat(this.value);
  var _thisMin = parseFloat(this.min);
  var _thisMax = parseFloat(this.max);

  if (_thisValue > _thisMax) {
    this.value = _thisMax.toFixed(1);
  } else if (_thisValue < _thisMin) {
    this.value = _thisMin.toFixed(1);
  } else {
    this.value = _thisValue.toFixed(1);
  }
}
英文:

This behavior is a result of comparing strings. First, this.value and this.max return strings from the HTML element, even after being assigned a number value. Second, the method toFixed() also returns a string. Instead we'll apply it after comparing values.

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

function setTwoNumberDecimal(event) {
  var _thisValue = parseFloat(this.value);
  var _thisMin = parseFloat(this.min);
  var _thisMax = parseFloat(this.max);

  if (_thisValue &gt; _thisMax) {
    this.value = _thisMax.toFixed(1);
  } else if (_thisValue &lt; _thisMin) {
    this.value = _thisMin.toFixed(1);
  } else {
    this.value = _thisValue.toFixed(1);
  }
}

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年6月1日 08:58:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76378069.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定