0

I am trying to print a value in a printchatbox with javascript. When you select a specific option from a 'select', I need that value to be printed. Right now what I made is this:

<div class='printchatbox' id='printchatbox'></div>
<select type='text' id='km' name='km' value=''>
  <option value='1'>Number 1</option>
  <option value='2'>Number 2</option>
 </select>

<script>
// elements
var inpKm = document.getElementById("km");
var chBox = document.getElementById('printchatbox');
// event at keyup
inpKm.addEventListener('keyup', verbruik);
// function with event
function verbruik() {
    var km = Number(inpKm.value.replace(',','.'));
    // check for '', null, undefined, false, 0, NaN
    if (!km) {
        chBox.innerHTML = 'Select option.';
    } else {
        chBox.innerHTML = km;
    }
}
</script>

But it doesn't work unfortunately, and I don't know why. The selection is not echoed into the chatbox. How can I fix it? Thanks in advance!

Here's a link to the code https://jsfiddle.net/3hLm0t9L/11/

aynber
  • 22,380
  • 8
  • 50
  • 63
Nour
  • 143
  • 1
  • 15
  • simply googling would get you the answer - https://stackoverflow.com/questions/1085801/get-selected-value-in-dropdown-list-using-javascript – kosher Feb 26 '18 at 02:09
  • 1
    Your code does work, it's just that you have to select an option from the dropdown and then hit any key. This is because you are using a `keyup` event rather than the `change` event. – Joseph Feb 26 '18 at 02:13
  • Thanks, that did the trick! – Nour Feb 26 '18 at 02:26

1 Answers1

1

It's because you bound a keyup event instead of the change event.

This line:

inpKm.addEventListener('keyup', verbruik);

Should be:

inpKm.addEventListener('change', verbruik);

Also, even if you're dutch, it's good practice to code in english. This to say, you should keep your variables etc. in english. It's just good practice and allows any programmer to interact with it.

NoobishPro
  • 2,539
  • 1
  • 12
  • 23
  • Thanks for the tip, will do that next time. Also, I changed the addEventListener to change and it works now, but only when I change the option selected from 1 to 2. Can I make it that it prints 1, say when you load the page? – Nour Feb 26 '18 at 02:25
  • 1
    @Nour use the `load` event: https://developer.mozilla.org/en-US/docs/Web/Events/load – Joseph Feb 26 '18 at 12:52
  • 1
    @Nour that's pretty simple. Just put `inpKm.change()` to manually trigger the eventlistener (AFTER setting it). By doing that you'll trigger it once. – NoobishPro Feb 26 '18 at 13:05