-1

I'm running into a little trouble trying to determine the value of an HTML select object.

I've got 2 items, which I'm putting down as Value 1 or Value 2, however any method I try just returns "Undefined" when printed to console

var catId = document.getElementById('catid');
var catCheck = catId.options[catId.selectedIndex].value;

console.log(catId);
console.log(catCheck);
<select name="catid" id="catid">
    <option value="1">Category</option>
    <option value="2">Product</option>
</select>

However when I console.log(catId.Value) or console.log(catCheck.value) (I'm obviously not trying both at the same time) I just returned an "Undefined" value.

I want to run an IF ELSE statement based on this variable, so ideally I'd like it to be able to pick up at least one of the two values!

Likelihood is I've made a dumb mistake and just can't see the wood for the trees but any help would be appreciated

Julian
  • 1,592
  • 1
  • 13
  • 33
Chris
  • 45
  • 9
  • 1
    Possible duplicate of [Get selected value in dropdown list using JavaScript?](https://stackoverflow.com/questions/1085801/get-selected-value-in-dropdown-list-using-javascript) – Robin Zigmond Dec 04 '18 at 09:01

2 Answers2

2

You could also get the selected <select> <option> like this:

var catCheck = document.getElementById("catid").selectedIndex;
console.log(catCheck);

Your first option would return 0, your second 1 and so on. You wouldnt have to use value this way.

Matt.S
  • 287
  • 4
  • 20
  • Thanks for the help! Made me realise my issue wasn't how I was trying to read the value but WHERE I was trying to read the value - once I moved the var inside the function it suddenly works without any issue! Many Thanks! The above definitely works for reading an index as well! – Chris Dec 04 '18 at 09:27
0

You can listen for the select element to change by adding an event listener for the change event. This will trigger the performDropdownAction function anytime you select a new value within the dropdown list. You can then use this.value to get the value of the current drop-down item you're on.

Also, I've added a window.onload event, which will fire when your webpage has loaded, meaning it will perform the performnDropdownAction when the page loads and when a new item is selected.

See working example below :

const performDropdownAction = function() {
  let current = this.value || document.getElementById('catid').value;
  if (current == 1) {
    console.log("One is selected");
  } else if (current == 2) {
    console.log("Two is selected");
  }
}

window.onload = performDropdownAction;

document.getElementById('catid').addEventListener('change', performDropdownAction);
<select name="catid" id="catid">
  <option value="1">Category</option>
  <option value="2">Product</option>
</select>
Nick Parsons
  • 45,728
  • 6
  • 46
  • 64