Say I have a select element with some options as shown below:
<select class="form-control" id="number-selector">
<option>One</option>
<option>Two</option>
<option>Three</option>
<option>Four</option>
<option>Five</option>
</select>
And a paragraph element
<p id="sh">Sheep</p>
What I am trying to do is have any of the options selected from the select element added to the front of the word in the p tag, so I can have One Sheep if one is selected, Two Sheep if Two is selected, and so on.
This is what I have tried but it just replaces the existing word in the p tag and other things that I have tried like insertBefore do not also work.
function getSelectedNumber() {
let selectedNumber = document.getElementById('number-selector');
let numb = selectedNumber.options[selectedNumber.selectedIndex];
let newText = document.getElementById('sh');
newText.innerHTML = "<span> " + numb.innerText + "</span> "+ newText.innerText;
}
This just keeps adding every new selection instead of replacing just the previously selected value so I get: "One Sheep" if I select One first, then if I select Two next I get "Two One Sheep" and so on. I want the previously selected option to be replaced by a new selection.
And for multiple elements, say:
<p id="sh">Sheep</>
<p id="of">Offspring</>
<p id="mu">Music</>
The JavaScript code:
function getSelectedNumber() {
let arr = ['sh','of','mu'];
let selectedNumber = document.getElementById('number-selector');
let numb = selectedVersion.options[selectedVersion.selectedIndex];
for(let i = 0; i < arr.length; i++){
let newText = document.getElementById(arr[i]);
newText.innerHTML = "<span> " + numb.innerText + "</span>" ;
}
}
But the code above just replaces the existing words in the p tags