CrimzonWeb CrimzonWeb - 5 months ago 8
Javascript Question

HTML JS How to display text about a dropdown list item

I have a programm where I want to have a dropdown list called DropDownGamer which i've made:

<select disabled="disabled" id="DropDownGamer">
<option disabled selected value>Valige Youtuber</option>
<option value="Terminats">Terminats</option>
<option value="HDTanel">HDTanel</option>
<option value="DeniedNetwork">DeniedNetwork</option>
<option value="Shroud">Shroud</option>
</select>


Now I have a checkbox that enables the dropdown list so you can choose from it. I want to make something like this: If you choose one of the items from the dropdown list, lets say you choose Terminats - the first item in the list, And press a button called ShowInfo, I want there to show up text below the button, about that item, something like this: Terminats has xxx subs and xxx views. I want to have custom text for each item.

I thought about something like this:

<input id="Button1" onclick="showInfo()" type="button" value="Show Info." />

function showInfo()
{
if (document.getElementById("Terminats"))
{

}
else if (document.getElementById("HDTanel"))
{

}
}


But I dont think that would work or atleast, I can't seem to get it to work.

Thanks!

Answer

one option would be to use a switch statement:

function showInfo() {
    var selectElement = document.getElementById("DropDownGamer");
    switch (selectElement.value) {
        case 'Terminants':
            // code to display text for terminants
            break;
        case 'HDTanel':
            // code to display text for hdtanel
            break;
        etc...
    }
}

best option would be to create an element after your button, let's say

<p id="description"></p>

and then something like

var description = document.getElementById('description');
description.removeChild(description.childNodes[0]);
var descriptionText = document.createTextNode("your description");
description.appendChild(descriptionText);

inside the respective case statement (you first target your element, then empty it if there is text inside, then create new text node and append it).

so full code would be:

var description = document.getElementById('description'),
    selectElement = document.getElementById('DropDownGamer');

function showInfo() {
    switch (selectElement.value) {
        case 'Terminants':
            description.removeChild(description.childNodes[0]);
            var descriptionText = document.createTextNode("your description for terminants");
            description.appendChild(descriptionText);
            break;
        case 'HDTanel':
            description.removeChild(description.childNodes[0]);
            var descriptionText = document.createTextNode("your description for hdtanel");
            description.appendChild(descriptionText);
            break;
        etc...
    }
}