简体   繁体   中英

Javascript function call from file

So...my homework says...

create a function named calcBMI() that performs the calculation using the values in the weight and height text boxes and assign the result to the BMI text box. Convert the value to an Integer number by using the parseInt() function. Reference the text boxes from within the function by using the documentobject.getElementByID(name), and the value attribute of each text box (in other words, don't use function arguments AKA pass values to the function). Add an event listener to to call the calcBMI() function

I have done that here. Keep in mind the javascript file is being reference in the html. Whenever I press the calculate button nothing happens.

  function calcBMI() {


    var weight = parseInt(documentobject.getElementByID("weight"));

    var height = parseInt(documentobject.getElementByID("height"));

    var result = (weight * 703) / (height * height);

    var textbox = documentobject.getElementById('Result');

    textbox.value = result;
}


 document.getElementById("submit").
      addEventListener("click", calcBMI(), false);

I see 3 things:

  1. accessing the DOM object rather than its value
  2. using documentobject rather than document
  3. invoking a function instead of passing it as a callback.

Here's to resolve the DOM element issue:
var weight = parseInt(document.getElementByID("weight").value)
Use the same for the other variables.

It looks like you may be invoking calcBMI() rather than passing it as a callback calcBMI
.addEventListener("click", calcBMI, false);

Check out MDN on event listeners

It also looks like you were referencing documentobject rather than document .

var textbox = documentobject.getElementById('Result');

Try this:
var textbox = document.getElementById('Result');

Hope this helps!

When calling addEventListener() you need to pass a reference to the callback function. You are calling the function, which is not correct. Try this instead:

document.getElementById("submit").addEventListener("click", calcBMI, false);

You assign dom elements to weight and height variables. You should get the value of the text field.

function calcBMI() {
    var weight = parseInt(document.getElementByID("weight").value);
    var height = parseInt(document.getElementByID("height").value);
    var result = (weight * 703) / (height * height);
    var textbox = document.getElementById('Result');
    textbox.value = result;
}

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