简体   繁体   中英

How to assign the user input value to a variable?

Here is my code

{
   var selectBox = document.getElementById("shapes");
   var selectedShape = selectBox.options[selectBox.selectedIndex].text;
   var tempSection = document.getElementById("emptySection");  
   var trianglelegend = document.getElementById("legend");
   trianglelegend.innerHTML = "Triangle Measurements"; 
   var baseLabel = createLabel("baseId", "Enter the base  here:");
   var heightLabel = createLabel("heightId", "Enter the height here:");
   var baseInput = createInput("baseId", "number"); 
   var heightInput = createInput("heightId", "number");
   tempSection.append(baseLabel,heightLabel,baseInput,heightInput); 
   document.getElementById("calculate").addEventListener("click", triangleCalculations); 
}

I am trying to the values the user entered in and use them in the function here below

{
    var height = document.getElementById("heightId");
    var base = document.getElementById("baseId");
    height = parseInt(height); 
    base = parseInt(base);
    var areaBox = document.getElementById("Area");
    areaBox.value = String(1/2 * base * height);
}

Where do I declare base and height variables to get the item the user enters in?

Document.getElementById() returns an Element . You can think of an element as a normal object with properties and methods that you can use.

Depending on the tag that has the id="heightId" , you may be able to access its value differently.

Since it's probable that your Element is an input, you can get the height by accessing its value property with var height = document.getElementById("heightId").value

You can find more info about different Elements and their methods/properties in the MDN Web Docs

To get value of label you need to write

var el = document.getElementById('heightId'); text = (el.innerText || el.textContent);

same with baseId

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM