简体   繁体   中英

Why is my JS function not printing in HTML (showing in console.log)

I'm new to coding and trying to make a basic volumetric calculator whereby you take length x breadth x height and divide by either 4000 or 5000 to get the volume in kg.

My select box function is working in the console but not printing the desired result to my html page.

Any assistance would be appreciated.

    // file volume.js

    let Lcm = prompt("Enter length in cm")
    let Bcm = prompt("Enter breadth in cm")
    let Hcm = prompt("Enter height in cm")
    
    
    function volume_4000(){
        let y = (+Lcm * +Bcm * +Hcm)/4000 +"kg"
        console.log(y)
        //document.getElementById("volume4000").innerHTML = y
    }
    
    
    
    function volume_5000(){
        let z = (+Lcm * +Bcm * +Hcm)/5000 +"kg"
        console.log(z)
        //document.getElementById("volume5000").innerHTML = z
    }
    
    
    function getSelectVolume(){
        let selectedVolume = document.getElementById("volume").value
        {
            if (selectedVolume === '4000:1') return volume_4000();
            if (selectedVolume === '5000:1') return volume_5000();
            
        }
        console.log(selectedVolume)
        
        
    }
    getSelectVolume()
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>Document</title>
    </head>
    <body>
        <h1>Volumetric calulator</h1>
        <h3>Please select your current volumetric factor:</h3>
       <select id= "volume" onchange="getSelectVolume()">
           <option value = "4000:1">4000:1</option>
           <option value = "5000:1">5000:1</option>
       </select>
        <h2 id="volume"></h2>
       <script src="volume.js"></script>
    </body>
    </html>

You need to write back your result to a HTML element in your DOM.

Eg insert this div to display the result:

<div id="volumeResult"></div>

Your calculation methods should return their result. I simplified them into a single method that takes the reduction factor as parameter.

function calculateVolume(reductionFactor) {
    var vol = (+Lcm * +Bcm * +Hcm)/reductionFactor +"kg"
    return vol;
}

Your main JS method can then call your calculation method and write its result back to the new div.

function getSelectVolume() {
    let selectedVolume = document.getElementById("volume").value;

    var result;
    if (selectedVolume === '4000:1') { result = calculateVolume(4000); } 
    if (selectedVolume === '5000:1') { result = calculateVolume(5000); }
    
    // error handling: what happens if another value is selected in the dropdown?
    result = 'Please select a factor (4000 or 5000)!';

    // write result to HTML to display it to the user
    document.getElementById('volumeResult').innerHTML = result;

   // optional: return calculation result so other JS code can use it
   return result;
}

BTW, are you sure the unit of measurement should be kg? The input values are given in cm, so your result should have dimensions of cm³. Or are you trying to calculate a weight? Then you should rename your methods to avoid confusion.

Another thing to think about: if you include the unit directly in the result, it will be hard to use the numeric value of the result for further calculations (it is converted to a string by appending 'kg' to the numeric value). Maybe return a structured result as object:

function calculateWeight(densityFactor) {
        var weight = (+Lcm * +Bcm * +Hcm)/densityFactor;
        return {
            'weight': weight, // number
            'unit':  'kg'     // string
        };
}

Then access the properties of the structured result object:

 var result1 = calculateWeight(5000);

 // append unit when displaying to the user
 document.getElementById('weightResult').innerHTML = result1.weight + ' ' + result1.unit;

// we can still calculate with the weight because it is a number
var totalWeight = result1.weight + result2.weight;

Is this what you are trying to achieve?

 let Lcm = prompt("Enter length in cm") let Bcm = prompt("Enter breadth in cm") let Hcm = prompt("Enter height in cm") function volume_4000() { let y = (+Lcm * +Bcm * +Hcm) / 4000 + "kg" document.getElementById("calculatedVolume").innerHTML = y } function volume_5000() { let z = (+Lcm * +Bcm * +Hcm) / 5000 + "kg" document.getElementById("calculatedVolume").innerHTML = z } function getSelectVolume() { let selectedVolume = document.getElementById("volume").value; // remove the curly brackets ('{' and '}') and // compact the two if clauses into a ternary operator selectedVolume === '4000:1' ? volume_4000() : volume_5000() console.log(selectedVolume) } getSelectVolume()
 <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Volumetric calulator</h1> <h3>Please select your current volumetric factor:</h3> <select id="volume" onchange="getSelectVolume()"> <option value="4000:1">4000:1</option> <option value="5000:1">5000:1</option> </select> <!-- change the H2 id to avoid conflicts --> <h2 id="calculatedVolume"></h2> <script src="volume.js"></script> </body> </html>

your html code need to like this

 <html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <h1>Volumetric calulator</h1>
    <h3>Please select your current volumetric factor:</h3>
   <select id= "volume" onChange="getSelectVolume()">
       <option value = "4000:1">4000:1</option>
       <option value = "5000:1">5000:1</option>
   </select>
    <h2 id="volume5000"></h2>
    <h2 id="volume4000"></h2>
   <script src="volume.js"></script>
</body>
</html>

and volume.js like this

  let Lcm = prompt("Enter length in cm")
let Bcm = prompt("Enter breadth in cm")
let Hcm = prompt("Enter height in cm")


function volume_4000(){
    let y = (+Lcm * +Bcm * +Hcm)/4000 +"kg"
    console.log(y)
    document.getElementById("volume4000").innerHTML = y
}



function volume_5000(){
    let z = (+Lcm * +Bcm * +Hcm)/5000 +"kg"
    console.log(z)
    document.getElementById("volume5000").innerHTML = z
}


function getSelectVolume(){
    let selectedVolume = document.getElementById("volume").value
    {
        if (selectedVolume === '4000:1') return volume_4000();
        if (selectedVolume === '5000:1') return volume_5000();
        
    }
    console.log(selectedVolume)
    
    
}
getSelectVolume()

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