Click here to Skip to main content
15,896,201 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to repeat this piece of code for multiple different dropdown boxes, however, I'm having real difficulties. I'm new to this, so the mistake may be really obvious! What bits of the code do I need to change so I can use it again?

 <script language="JavaScript">

var DivTxt = new Array()
DivTxt[1] = "Most magnets have a North Pole and a South Pole. Two of the same poles will not get on and will, therefore, repel each other. However, opposite poles will attract each other, so will form the best relationships."
DivTxt[2] = "Most magnets have a North Pole and a South Pole. Two of the same poles will not get on and will, therefore, repel each other. However, opposite poles will attract each other, so will form the best relationships."

function getText(slction){
txtSelected = slction.selectedIndex;
document.getElementById('textDiv').innerHTML = DivTxt[txtSelected];
}
</script>
  
 <label for="critical">I am looking for</label> 
  
<Select class="body_text" name="critical" onchange="getText(this)" style="height:30px;">
<option value="Select"> Select </option>
   <option value="North Pole"> North Pole </option>
   <option value="South Pole"> South Pole </option>    
</select>
<div id="textDiv" style="color:black; font-family:ariel; font-size:15px; font-weight:regular"> </div>


What I have tried:

Tried changing the DivTxt numbers.
Posted
Updated 12-Mar-21 21:49pm

You need to put the code in a JavaScript Functions[^]. You can then call it multiple times with different parameter values.
 
Share this answer
 
Check this link below, maybe this kind of solution resolve your problem.

https://codepen.io/onurodemis/pen/poNYPKa
 
Share this answer
 
Comments
onur_odemis 14-Mar-21 14:42pm    
Or try this

function getText(slction, textDiv) {
txtSelected = slction.selectedIndex;
document.getElementById(textDiv).innerHTML = DivTxt[txtSelected];
}

<select class="body_text" name="critical" onchange="getText(this, 'textDiv')" style="height:30px;">
  <option value="Select"> Select </option>
    <option value="North Pole"> North Pole </option>
    <option value="South Pole"> South Pole </option>    
  </select>

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900