0

I am trying to figure out what's wrong with my script. When the input reaches 1, it should display the alert but it does't. But if i replace (value === 1) with (value === value), it displays the alert every time i change the input. So i know the problem is with the syntax "(value === 1)". I tried everything. 5 hours weren't enough for me to find a solution on the internet, so i hope someone tells me if i made mistake with the syntax or something. Thank you for your time.

<input id="carrotate123" type="range" min="0" max="3" value="2" oninput="getInput(this.value)">

<script>
function getInput(value) {
    var rangeInput = document.getElementById("carrotate123").value;
    var value = rangeInput.value;
    if (value === 1) { 
        alert("First"); 
    }
  
}
</script>
  • Are you sure you need `===`? https://stackoverflow.com/q/5447024/1531971 (What type is `value`? Is it something that makes sense to compare in this manner with `1`?) –  Nov 08 '18 at 15:47

2 Answers2

4

The === operator means strict equality - both in value and in type. In your case, value is a string (value property of DOM elements usually returns a string) while 1 is obviously a number. Consider the examples below:

1 == 1 // true
1 == "1" // true
1 === 1 // true
1 === "1" // false

You should consider changing === to == (which performs automatic type coercion) or compare your value with "1" (as a string).

More about differences between comparison operators: Expressions and operators

Szab
  • 1,263
  • 8
  • 18
1

You have two things wrong here. First, you have an extra call to value. The cleanest solution to that is to remove the one on the rangeInput assignment. But you could also simply use that value and skip defining rangeInput altogether.

The second one is covered in the answer from Szab. You need to change how you compare your target value with the String supplied by the input element. Combining these looks like this:

<input id="carrotate123" type="range" min="0" max="3" value="2" oninput="getInput(this.value)">

<script>
function getInput(value) {
    var rangeInput = document.getElementById("carrotate123");
    var value = rangeInput.value;
    // or replace the previous two lines with
    // var value = document.getElementById("carrotate123").value
    if (value == 1) { // or: if (value === '1')
        alert("First"); 
    }
  
}
</script>
Scott Sauyet
  • 49,207
  • 4
  • 49
  • 103