0

There are two values in function. Input and select, everything works normally except that the select returns the first value (px). Where did I get it wrong?

<input id="width" onchange="Width()" type="number" placeholder="0" min="" max="" step="0.1">

<select id="widthpixselpercentage" onchange="Width()" >
<option value="px">px</option>
<option value="%">%</option>
</select>

<div id="someDiv"></div>
function Width(){
var x = document.getElementById("width").value;
var y = document.getElementById("widthpixselpercentage").value;
        document.getElementById(someDiv).style.width = x + y;

}
  • option is an option of the select box, select has no 'value' it has a selectedIndex which you can use to find out which option the user has selected – Jay May 27 '19 at 11:08
  • Close your input tag at the end /> also, you mean it is not being listed or the JS cannot catch it? – Daniel Danaee May 27 '19 at 11:08
  • Possible duplicate of [Get selected value in dropdown list using JavaScript?](https://stackoverflow.com/questions/1085801/get-selected-value-in-dropdown-list-using-javascript) – Michel May 27 '19 at 11:20
  • @Jay That was the situation for twenty years ago, nowadays `select` element has a value, which reflects the value of the selected option. – Teemu May 27 '19 at 11:27

2 Answers2

1

If you want value from select box by using javascript:

var select_box = document.getElementById("widthpixselpercentage");
var y = select_box.options[select_box.selectedIndex].value;

If you want text from select box by using javascript:

var select_box = document.getElementById("widthpixselpercentage");
var y = select_box.options[select_box.selectedIndex].text;

Please try the following:

function Width(){
var x = document.getElementById("width").value;
var select_box = document.getElementById("widthpixselpercentage");
var y = select_box.options[select_box.selectedIndex].value;
        document.getElementById("someDiv").style.width = x + y;

}
#someDiv{
border:1px solid;
height:5px;
}
<input id="width" onchange="Width()" type="number" placeholder="0" min="" max="" step="0.1">

<select id="widthpixselpercentage" onchange="Width()" >
<option value="px">px</option>
<option value="%">%</option>
</select>

<div id="someDiv"></div>
Maths RkBala
  • 2,207
  • 3
  • 18
  • 21
0

You may refer to the following sample code:

function Width(vv)
{
 alert(vv.value);
}
<input id="width" onchange="Width(this)" type="number" placeholder="0" min="" max="" step="0.1">

<select id="widthpixselpercentage" onchange="Width(this)" >
<option value="px">px</option>
<option value="%">%</option>
</select>

<div id="someDiv"></div>
The KNVB
  • 3,588
  • 3
  • 29
  • 54