0

I am trying to check if some option has been selected from a drop-down list in javascript. When the user selects an item in the drop-down list, the below change event function, is triggered. The value is a string that either contains an empty string "" or a numeric value such as "0", "1", "2", "3", etc.

function (event, value) {
   if (value >=0)
   {
      // Do some stuff here
   }
});

If an item has been selected from the drop down list (value >=0 but not empty) I want to execute some code. In above snippet code, the conditional body is always executed regardless of whether the value is empty or not. It does not work.

Which is the best way to check if coming value is a number (not empty string) and if so then check if that value is greater than 0?

Expected results are:

  • value == "" -> Conditional body should not be executed

  • value != "" and value >= 0 -> Conditional body should be executed.

Tom
  • 4,070
  • 4
  • 22
  • 50
Willy
  • 9,848
  • 22
  • 141
  • 284
  • 1
    Convert it to a number and compare numerically. See the answers to the [linked question](https://stackoverflow.com/questions/32945779/incorrect-result-in-javascript-calculation) for details. Beware that some of the convert-to-number options will convert `""` to `0`, which you probably don't want. But for instance, `if (value && +value >= 0)` would only be true if `value` wasn't an empty string, it contained only text that could be successfully converted to number, and the resulting number is `>= 0`. – T.J. Crowder Dec 17 '20 at 10:27

1 Answers1

0

You need to get the selected option from the drop down, via the selectedIndex property on the event listener target. Then you need to get the value of the option to be able to compare it. See the code below.

document.getElementById('numbers').addEventListener('change', e => {
    let target = e.currentTarget;
    let value = target.options[target.selectedIndex].value;
    if(value > 0) {
       alert("bigger than 0");
    }
});
<label for="numbers">Please select a number</label>
<select id="numbers">
   <option value="0">0</option>
   <option value="1">1</option>
   <option value="2">2</option>
   <option value="3">3</option>
</select>
Tschallacka
  • 27,901
  • 14
  • 88
  • 133