1

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 ?

2 Answers 2

1

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;
})
Sign up to request clarification or add additional context in comments.

3 Comments

No mater what I use I get this: api.openweathermap.org/data/2.5/… I tried select, text, textEL, cityID, e and all the same basic result?
I need to insert the value into this line: api.openweathermap.org/data/2.5/weather?q=' + variable from dropdown select + '&appid=' + key)
Well I added to the code and now the variable is being passed correct, but while the select box shows the selections and it works, the <script> section is not refreshing on any changes. What ever is the first value is in the list it just stays that.
1
  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>

Comments

Your Answer

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