I have a pug file that dynamically populates a dropdown from a list of objects (customers), but I can't seem to get the value that is currently selected from it. Here is the code:
select(name="customerDropdown", id="customerDropdown" class="btn btn-success dropdown-toggle")
each customer in customers
option=customer
script.
var el = document.getElementById('customerDropdown');
var strCustomer = el.options[el.selectedIndex].text;
strCustomer doesn't seem to hold any value after this. Any help apprecited!
Please try the following code and see how it works on your side:
- var customers = ['John','Maria','Nicolas']
select(name="customerDropdown", id="customerDropdown" class="btn btn-success dropdown-toggle")
each customer in customers
option=customer
script.
var $customerDropdown = document.getElementById('customerDropdown');
var getSelectedCustomer = function() {
return $customerDropdown.options[$customerDropdown.selectedIndex].text
}
$customerDropdown.addEventListener('change', function(event) {
alert('new value: ' + getSelectedCustomer())
});
alert(getSelectedCustomer())
It should alert the first value in the select box (John
) when the app is launched and later on when you change the select option - it should alert the selected one. E.g. if you select Nicolas
it should alert (new value: Nicolas
)
Hope this will give you the idea on how to handle select element.