Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
Change var value from dropdown in javascript with onchange

I have a dropdown list which looks like this:

<select id="cityID">
        <option value="mission">Mission</option>
        <option value="bakersfield">Bakersfield</option>
        <option value="knoxville">Knoxville</option>
</select>

And my code to get the value is:

var select = document.getElementById('cityID');
var text = select.options[select.selectedIndex].text;
text.innerHTML = cityID.value;

text.onchange = function(e) {
   text.innerHTML = e.target.value;
}

The value always chooses the first item. How can I get it to accept the cityID and change the page,

I'm sure its a formatting or typo or wrong value ?

about 4 years ago · Santiago Gelvez
2 answers
Answer question

0

  1. onchange event is trigger from the select element
  2. your text variable seems to be an HTML element because you set its innerHTML property
  3. a select element has a "value" property so you don't need to get it from the selectedIndex of the options.

var select = document.getElementById('cityID');
var textEl = document.getElementById("text")
text.innerHTML = select.value;

select.onchange = function(e) {
   textEl.innerHTML = e.target.value;
}
<select id="cityID">
        <option value="mission">Mission</option>
        <option value="bakersfield">Bakersfield</option>
        <option value="knoxville">Knoxville</option>
</select>

<p id="text"></p>

about 4 years ago · Santiago Gelvez Report

0

You could achieve this using addEventListener also.

var select = document.getElementById('cityID');
var textEl = document.getElementById("text")
select.addEventListener("change", (e) => {
    textEl.innerText = e.target.value;
})
about 4 years ago · Santiago Gelvez Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!