user10523311
user10523311

Reputation:

Javascript, if input type range condition

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>

Upvotes: 0

Views: 334

Answers (2)

Scott Sauyet
Scott Sauyet

Reputation: 50787

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>

Upvotes: 1

Szab
Szab

Reputation: 1263

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

Upvotes: 4

Related Questions