1

I have a selection of properties with the div id of property_id that passes an id value. I have an event listener that triggers when a user selects a property. I want to create a conditional that checks if the property selection is in the array.

document.getElementById('property_id').addEventListener('change', function (e) {
 var array = [1, 17, 20, 23, 87]
 var propertySelection = e.target.value;
 if (array.includes(propertySelection)) {
   //do stuff
 }
});

Doing console.log(propertySelection) provides the correct number when selecting properties (ie. 17, 2, 20 etc), but doing console.log(array.includes(propertySelection)) outputs false on all accounts. Why is this?

DollarChills
  • 1,076
  • 1
  • 15
  • 33

1 Answers1

1

The issue is that input values from the page are always returned as strings:

const val = document.getElementById('property_id').value;

console.log(val, typeof val)
<input type="number" value=20 id="property_id" />

Which then means that when using Array#includes() on an array of numbers, no match can be found:

var array = [1, 17, 20, 23, 87];
var propertySelection = "20";

console.log(array.includes(propertySelection));

Instead, the most direct way to get a numeric value from an input is using .valueAsNumber

document.getElementById('property_id').addEventListener('change', function(e) {
  var array = [1, 17, 20, 23, 87]
  var propertySelection = e.target.valueAsNumber;
  // get numeric value directly    ^^^^^^^^^^^^^
  if (array.includes(propertySelection)) {
    console.log("do stuff");
  } else {
    console.log("don't do anything");
  }
});
<input type="number" id="property_id" />

Alternative is using Number as a function to convert a string value to a number:

document.getElementById('property_id').addEventListener('change', function(e) {
  var array = [1, 17, 20, 23, 87]
  var propertySelection = Number(e.target.value);
  // convert to number    ^^^^^^^              ^
  if (array.includes(propertySelection)) {
    console.log("do stuff");
  } else {
    console.log("don't do anything");
  }
});
<input type="number" id="property_id" />

For completeness, the you can also

  • a unary plus which is exactly the same as calling Number.
  • parseFloat which will do basically the same however parseFloat("123.4abc") is 123.4 while Number("123.4abc") and +"123.4abc" would return NaN
  • parseInt if you prefer only integers.
VLAZ
  • 26,331
  • 9
  • 49
  • 67