Desmond97
Desmond97

Reputation: 37

JavaScript/HTML - Add up the values from dropdown list and textbox

just want to ask that how to extract the values from dropdown list and from textbox, then total up them together and display the total? I googled around and tried different ways but it did not worked. Still learning in HTML and JavaScript.

What is your height? (centimetres)
<select>
  <option name="height1" value="100">100cm</option>
  <option name="height1" value="101">101cm</option>
  <option name="height1" value="102">102cm</option>
  <option name="height1" value="103">103cm</option>
  <option name="height1" value="104">104cm</option>
  <option name="height1" value="105">105cm</option>
</select>
<br><br> What is your weight? (kg)
<input type="number" id="weight1" step="0.01" name="weight" pattern="\d{4}" autocomplete="off"><br><br> BMI: <input type="text" id="txtresult" name="bmi" readonly>
<input type="button" name="calculate" value="Calculate" onclick="calculate_bmi()">

function calculate_bmi()
{
	/*var h = parseFloat(document.getElementById("height1").value);
	var w = parseFloat(document.getElementById("weight1").value);
	if ((h != parseFloat(h, 10)) || (w != parseFloat(w, 10)))
		alert("Must insert number")
	if ( ( h <= 0 ) || ( w <= 0 ) )
		alert("Please insert positive numbers")
	if ( ( h >= 2.7 ) || ( w >= 500 ) )
		alert("Out of range");
	else
	{
		var result = w / h / h;
		result = Math.round(result * 100) / 100;
		document.getElementById("txtresult").value = result;
	}*/
	var h = document.getElementsByName("height1");
	//h = h / 100;
	var w = parseFloat(document.getElementById("weight1").value);
	var result = 0;
	for (var i = 0; i < h.length; i++)
	{
		if(h[i].tagName == 'SELECT')
		{
			//result = w / Number(h[i].options[h[i].selectedIndex].value);
			result = h + w;
		}
		if (h[i].checked)
		{
			//result = parseFloat(h[i].value);
			result = h + w;
		}
	}
	document.getElementById("txtresult").value = result.toFixed(2);
}

And I follows some solutions that available in Internet but it cannot works. The textbox values worked (commented code) but I want to use dropdown list and textbox to sum up together but I failed. Note: Just want to sum up things together. Because I want to know how to get and add the values inside the dropdown list and textbox. Then I will do the rest of them (calculating BMI).

Thanks in advance.

Upvotes: 3

Views: 250

Answers (4)

Nick Parsons
Nick Parsons

Reputation: 50884

To get the value from the dropdown/select element, you can use:

document.querySelector('select').value;

This will give you a string (words), however, since you want to do calculations with this input you need it to be a number (integer, float etc...) so we can use a + in front of this statement to convert it to a number:

+document.querySelector('select').value;

However, I recommend that you add an id to your select element so you can target it like so (adding an id will improve your code's runtime):

+document.getElementById('height').value;

To get the value from your textbox, you can do:

+document.getElementById('weight1').value;

Here we are also converting it to a number by using the + operator.

Lastly, to set the bmi's textbox to the calculated value you can use:

document.getElementById("txtresult").value = bmi;

See working example below:

function calculate_bmi() {
  let height = +document.getElementById("height").value;
  let weight = +document.getElementById("weight1").value;
  let bmi = height + weight; // perform bmi calculation here
  document.getElementById("txtresult").value = bmi;
}
What is your height? (centimetres)
<select id="height">
  <option name="height1" value="100">100cm</option>
  <option name="height1" value="101">101cm</option>
  <option name="height1" value="102">102cm</option>
  <option name="height1" value="103">103cm</option>
  <option name="height1" value="104">104cm</option>
  <option name="height1" value="105">105cm</option>
</select>
<br><br> What is your weight? (kg)
<input type="number" id="weight1" step="0.01" name="weight" pattern="\d{4}" autocomplete="off"><br><br> BMI: <input type="text" id="txtresult" name="bmi" readonly>
<input type="button" name="calculate" value="Calculate" onclick="calculate_bmi()">

Upvotes: 2

lloydaf
lloydaf

Reputation: 605

This code worked for me. I modified your html a bit and added an id to the select box.

  function calculate_bmi() {
          /*var h = parseFloat(document.getElementById("height1").value);
    	var w = parseFloat(document.getElementById("weight1").value);
    	if ((h != parseFloat(h, 10)) || (w != parseFloat(w, 10)))
    		alert("Must insert number")
    	if ( ( h <= 0 ) || ( w <= 0 ) )
    		alert("Please insert positive numbers")
    	if ( ( h >= 2.7 ) || ( w >= 500 ) )
    		alert("Out of range");
    	else
    	{
    		var result = w / h / h;
    		result = Math.round(result * 100) / 100;
    		document.getElementById("txtresult").value = result;
    	}*/
          var selectBox = document.getElementById("selectBox");
          var h = parseFloat(selectBox.value);
          //h = h / 100;
          var w = parseFloat(document.getElementById("weight1").value);
          var result = h+w;
          document.getElementById("txtresult").value = result.toFixed(2);
        }
 <html>
      <body>
        What is your height? (centimetres)
        <select id="selectBox">
          <option name="height1" value="100">100cm</option>
          <option name="height1" value="101">101cm</option>
          <option name="height1" value="102">102cm</option>
          <option name="height1" value="103">103cm</option>
          <option name="height1" value="104">104cm</option>
          <option name="height1" value="105">105cm</option>
        </select>
        <br /><br />
        What is your weight? (kg)
        <input
          type="number"
          id="weight1"
          step="0.01"
          name="weight"
          pattern="\d{4}"
          autocomplete="off"
        /><br /><br />
        BMI: <input type="text" id="txtresult" name="bmi" readonly />
        <input
          type="button"
          name="calculate"
          value="Calculate"
          onclick="calculate_bmi()"
        />
      </body>
      <script>
      
      </script>
    </html>

Upvotes: 0

Angelos Chalaris
Angelos Chalaris

Reputation: 6763

You can use document.getElementsByName("height1")[0] to get the desired element, then use h.options[h.selectedIndex].value to find the selected value. Then, you can use parseFloat as usual:

function calculate_bmi() {
  var h = document.getElementsByName("height1")[0];
  h = parseFloat(h.options[h.selectedIndex].value);
  // h = h / 100;
  var w = parseFloat(document.getElementById("weight1").value);
  console.log(h, w);
  var result = h + w;
  document.getElementById("txtresult").value = result.toFixed(2);
}
What is your height? (centimetres)
<select name="height1">
  <option value="100">100cm</option>
  <option value="101">101cm</option>
  <option value="102">102cm</option>
  <option value="103">103cm</option>
  <option value="104">104cm</option>
  <option value="105">105cm</option>
</select>
<br><br> What is your weight? (kg)
<input type="number" id="weight1" step="0.01" name="weight" pattern="\d{4}" autocomplete="off"><br><br> BMI: <input type="text" id="txtresult" name="bmi" readonly>
<input type="button" name="calculate" value="Calculate" onclick="calculate_bmi()">

As a side note, name should be added to the control (i.e. the <select> element) and not the values inside it (i.e. the <option> elements).

Upvotes: 2

SamuelB
SamuelB

Reputation: 155

If you are trying to get the value from the dropdown list. Get the Select element by name which stores it as an array, then run a for loop through the list and extract the value. See below,

function calculate_bmi() {
    var value = 0;
    var h = document.getElementsByName("height1");
    for(var i = 0; i<h.length; i++){
        if(h[i].selected){
            value = h[i].value
            // Do something with the value
        }
    }
}

Upvotes: 0

Related Questions