0

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?

2
  • The code you provided works as intended. Maybe it comes from somewhere else? jsfiddle.net/u2fnv8xk Commented Mar 22, 2020 at 15:02
  • Okay, so I didn't notice that Jquery was added. And my function used a taken name. Thank you! Commented Mar 22, 2020 at 15:33

1 Answer 1

2

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.