简体   繁体   中英

Javascript beginner - Can anyone tell me why my button doesn't work?

jsfiddle is here --> http://jsfiddle.net/diabetesjones/015k1tjn/5/

here's an example of one that does work: http://jsfiddle.net/Ahopefulmachine/dkhj8o38/

Regarding the second jsfiddle (not mine), I don't quite get why his works without using document.getElementById on the button.

i feel like my problem is in the click function itself of :

document.getElementById('mainButton').onclick = function () {

thanks :)

working now: http://jsfiddle.net/doniyor/015k1tjn/9/

you had document.getElementByID which should be document.getElementById

AND

  1. you didnot convert strings to int like numberOne = parseInt(numberOne, 10); where 10 is radix for decimal.
  2. you had question == ADD which should be question == 'ADD'

There are three things wrong with your code:

  1. It's getElementById not getElementByID (case-sensitive).
  2. You didn't convert the strings you get from the input to numbers. You can do this easily by adding a + in front of the document.getElementById('number1').value;
  3. You were doing comparisons against variables, not strings. Ex question == ADD instead of question == 'ADD'

See corrected jsFiddle example

document.getElementById('mainButton').onclick = function () {

    //Getting values of inputs and saving them to variables
    var numberOne = +document.getElementById('number1').value;
    var numberTwo = +document.getElementById('number2').value;

    //Setting values of the equations
    var addition = (numberOne + numberTwo);
    var subtraction = (numberOne - numberTwo);
    var multiplication = (numberOne * numberTwo);
    var division = (numberOne / numberTwo);

    //Prompting user for their desired equation
    var question = prompt("Do you wish to ADD, SUBTRACT, MULTIPLY, or DIVIDE?").toUpperCase();

    //If statement to show the proper equation based on the user's prior prompt
    if (question == 'ADD') {
        alert('I added the shit out of those numbers for you - turns out it is ' + addition);
    } else if (question == 'SUBTRACT') {
        alert('Did some of this, some of that, some minusing - your answer is ' + subtraction);
    } else if (question == 'MULTIPLY') {
        alert('Yeah, I multipled the numbers, big whoop, wanna fight abouddit? the answers over there --> ' + multiplication);
    } else if (question == 'DIVIDE') {
        alert('This ones my favorite, I love a good division - ' + division);
    };

};

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