Reputation: 27
I have a select tag:
//$places = Array("A", "B", "C");
<select onchange="calculate()" class="form-control" id="from" name="from">
<?php foreach($places as $place){
echo '<option value="'.$place.'">'.$place.'</option>';
} ?>
</select>
And I need to get the selected option's value with js. I tried like this:
function $(id){return document.getElementById(id);}
function calculate() {
var from = $("from").value;
var to = $("to").value;
console.log(from);
console.log(to);
.
.
.
}
But that gives back 'undefined'. Any Ideas?
Upvotes: 0
Views: 49
Reputation: 6390
Instead of using inline onchange
add an event listener to the select by javascript.
const sel = document.querySelector('#sel');
sel.addEventListener('change', function(e) {
console.log(e.target.value);
});
<select name="sel" id="sel">
<option value="A">A</option>
<option value="B">B</option>
<option value="C">C</option>
</select>
Upvotes: 2