Arszenik Arszenik - 1 month ago 6
HTML Question

Getting JS to read the selection from a HTML <select> form

So I am trying to write a piece of JS code that will get the selected option from a HTML form, read it and then give me something back depending on what the option was.

The HTML code looks like this:

<select id="mainhand" name="Main hand" onchange="getmh()">
<option value="Sword" selected> Sword </option>
<option value="Axe"> Axe </option>
<option value="Mace"> Mace </option>
</select>
<p id="mhchoice">choice</p>
<p id="mhdesc">description</p>
<p id="mhcost">cost</p>


and the JS like this:

function getmh(option){
if (option == "Sword"){
document.getElementById('mhchoice').innerHTML = 'Sword';
document.getElementById('mhdesc').innerHTML = swordDesc;
document.getElementById('mhcost').innerHTML = swordPrice;
document.getElementById('ProductImage').src = 'sword.png';
}
if (option == "Axe"){
document.getElementById('mhchoice').innerHTML = 'Axe';
document.getElementById('mhdesc').innerHTML = axeDesc;
document.getElementById('mhcost').innerHTML = axePrice;
document.getElementById('ProductImage').src = 'axe.png';
}
if (option == "Mace"){
document.getElementById('mhchoice').innerHTML = 'Mace';
document.getElementById('mhdesc').innerHTML = maceDesc;
document.getElementById('mhcost').innerHTML = macePrice;
document.getElementById('ProductImage').src = 'mace.png';
}
}


Ive been stuck on this for nearly two hours now, ive tried multiple things but nothing seems to work so far.

Answer

As @nnnnnn mentioned in the Above comment, you've just to pass the selected value this.value to the function :

<select id="mainhand" name="Main hand" onchange="getmh(this.value)">

Hope this helps.

function getmh(option){
  if (option == "Sword"){
    document.getElementById('mhchoice').innerHTML = 'Sword';
    document.getElementById('mhdesc').innerHTML = swordDesc;
    document.getElementById('mhcost').innerHTML = swordPrice;
    document.getElementById('ProductImage').src = 'sword.png';
  }
  if (option == "Axe"){
    document.getElementById('mhchoice').innerHTML = 'Axe';
    document.getElementById('mhdesc').innerHTML = axeDesc;
    document.getElementById('mhcost').innerHTML = axePrice;
    document.getElementById('ProductImage').src = 'axe.png';
  }    
  if (option == "Mace"){
    document.getElementById('mhchoice').innerHTML = 'Mace';
    document.getElementById('mhdesc').innerHTML = maceDesc;
    document.getElementById('mhcost').innerHTML = macePrice;
    document.getElementById('ProductImage').src = 'mace.png';
  }   
}
<select id="mainhand" name="Main hand" onchange="getmh(this.value)">
  <option value="Sword" selected> Sword </option>
  <option value="Axe"> Axe </option>
  <option value="Mace"> Mace </option>
</select>
<p id="mhchoice">choice</p> 
<p id="mhdesc">description</p>
<p id="mhcost">cost</p>