1

I have a drop down menu that, when clicked, successfully changes the image's thumbnail. But, I also need the <p> text to change. I looked at W3Schools, and still to no avail. Here is my code.

<p id="caption"></p>
<select name="woodType" id="woodType" onChange="changeThumbnail();changeCaption(this);">

<script>
    function changeCaption(selTag) {
        var caption = selTag.options[selTag.selectedIndex].text;
        document.getElementById("caption").text = "Wood: " + caption;
    }
</script>

The text will NOT change.

potashin
  • 44,205
  • 11
  • 83
  • 107
user3547286
  • 15
  • 1
  • 6

3 Answers3

5

Try the following :

 <script>
     function changeCaption(selTag) {
         var caption = selTag.value;
         document.getElementById("caption").innerHTML = "Wood: " + caption;
     }
 </script>

You should use innerHTML property to set or return the text of the <p> element.

potashin
  • 44,205
  • 11
  • 83
  • 107
  • 2
    Yep, you beat me to it. `.text()` is a jQuery shortcut, not a native JavaScript method – jshanley Apr 18 '14 at 03:05
  • 1
    -1 `.text` sets / returns text of an option . and `p` does not have text property so you should use `innerHTML` .As you good practice you should always mention behavior of you change – Deepak Ingole Apr 18 '14 at 03:10
  • @user3547286 : have you got any error in your js console? However, this issue could occur due to using 2 js function on the same event, so you can try to wrap your functions in one and see if it helps. Also read: http://stackoverflow.com/questions/3910736/onclick-multiple-javascript-functions – potashin Apr 18 '14 at 03:24
  • no error. could it be because of my divs? maybe I don't have one closed somewhere – user3547286 Apr 18 '14 at 03:33
1

.text is property of option elements not p.To set p text you should be using .innerHTML,

function changeCaption(selTag) {
    var caption = selTag.options[selTag.selectedIndex].text;
    document.getElementById("caption").innerHTML = "Wood: " + caption;
}

DEMO

Deepak Ingole
  • 14,912
  • 10
  • 47
  • 79
0

document.getElementById returns a reference to a DOM element. You can think of few candidates you can use on the Element object namely textContent, innerHTML and innerText (not working in Firefox)

If you read the article here and documentation on developer.mozilla.org you'll notice that its better use textContent than using innerHTML for your requirement.

In the Mozilla documentation for innerHTML under security considerations it says,

It is recommended you not use innerHTML when inserting plain text; instead, use node.textContent. This doesn't interpret the passed content as HTML, but instead inserts it as raw text.

Community
  • 1
  • 1
Nipuna
  • 6,846
  • 9
  • 64
  • 87