0

I want to have a dropdown that lists different bird species and I want each option to display a unique paragraph and image for that species. The below code is almost working for me, however on page load I would like the first option to be automatically selected.

  1. How do I do this?

  2. Is this the best way to go about this?

I am new to this and any help would be much appreciated. Thanks

https://jsfiddle.net/h0m0cpxk/

<html>
<body>
  
<select id="opts" selected="selected" onchange="document.getElementById('ExtraInfo').firstChild.nodeValue = this.options[this.selectedIndex].getAttribute('extrainfo')">
  
  <option value="buzzard" extrainfo="The buzzard is by far the most common of all our birds of prey, and its expansion has been dramatic">Buzzard</option>
  <option value="redkite" extrainfo="The red kite is a medium-large bird of prey in the family Accipitridae, which also includes many other diurnal raptors such as eagles, buzzards, and harriers">Red kite</option>
  <option value="sparrowhawk" extrainfo="Habitat and food availability remain the main limiting and controlling factors of sparrowhawk numbers">Sparrow hawk</option>
  
</select>

<div id="ExtraInfo">extra</div>

</body>
</html>
user3821345
  • 648
  • 1
  • 11
  • 33

2 Answers2

2

One simple way is to add the the first option text to your ExtraInfo div by default. Since the first option in a select list is automatically selected when page is loaded, it will serve your purpose.

<div id="ExtraInfo">The buzzard is by far the most common of all our birds of prey, and its expansion has been dramatic</div>
1

The first option will automatically be selected. You might not need to trigger the change event here. You can just write the first paragraph into the <p> in HTML; it will be overwritten when you select a different option.

The other way to do it is to trigger the onchange event via Javascript on page load. This is a bit tricky without jQuery, see this question:

https://stackoverflow.com/a/2856602/5742681

Community
  • 1
  • 1
KWeiss
  • 2,954
  • 3
  • 21
  • 37