I set up two events, one in feet and one in inches. I'm trying to grab the value of each event which would be feet and inches but I can't because of each event's scope. Is there a way to pass both values into my totalHeight function so that I can add the two values together?
const justFeet = totalFeet.addEventListener('input', (e) => { const heightInFeet = e.target.value; let displayFeet = document.createElement('h3') displayFeet.textContent = heightInFeet * 12 // totalInches.appendChild(displayFeet) }) const justInches = inches.addEventListener('input', (e) => { const addOnInches = e.target.value; let displayInches = document.createElement('h3') displayInches.textContent = addOnInches // totalInches.appendChild(displayInches) }) function totalHeight (feet, inches) { const finalTotal = feet + inches; let finalHeight = document.createElement('h3') finalHeight.textContent = finalTotal totalInches.appendChild(finalHeight) } totalHeight(displayFeet, displayInches)
An example of what it looks like you are trying to do. There's more you need to do, for example I used integers below but you could use floating numbers and perhaps add better handling for isNaN().
<html>
<style>
</style>
Feet:<input id="feet" type="number"></input>
Inches:<input id="inches" type="number"></input>
<h3>Feet converted to inches: <span id="displayFeetToInches"></span></h3>
<h3>Inches: <span id="displayInches"></span></h3>
<h3>Total inches:<span id="finalHeight"></span></h3>
<script>
const feet = document.getElementById("feet");
const inches = document.getElementById("inches");
const total = document.getElementById("total"); //in inches
const displayFeetToInches = document.getElementById("displayFeetToInches"); //in inches
const displayInches = document.getElementById("displayInches"); //in inches
const justFeet = feet.addEventListener('input', (e) => {
console.log('justFeet');
const heightInFeet = e.target.value;
displayFeetToInches.textContent = heightInFeet * 12;
totalHeight();
})
const justInches = inches.addEventListener('input', (e) => {
console.log('justInches');
const addOnInches = e.target.value;
displayInches.textContent = addOnInches
totalHeight();
})
function totalHeight (feet, inches) {
console.log('totalinches');
const ftToInches = displayFeetToInches.textContent;
const addOn = displayInches.textContent;
const finalTotal = parseInt(ftToInches) + parseInt(addOn);
finalHeight.textContent = finalTotal
}
</script>
</html>
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.