Question

I am building a basic jQuery calculator. Everything was going good, until I tried doing the reciprocal function. I have it bound to a click event. The code looks like this

// inverse is $(".row li.inverse")
inverse.on("click", function () {
    // textBox is $("input#result")
    var val = textBox.val(),
        text = parseFloat(val),
        recip = eval(1/text);
    textBox.val(recip);
});

So on the click of the button with the class inverse, it should get the value of what is in the input, and turn it into a number. It should then eval the number as 1 divided by the number, and set the textbox value equal to the answer. But when I click the button, the value stays the same. However, when I put the code into firebug without the click handler, it works just fine. Where am I going wrong?

Fiddle

Was it helpful?

Solution

You have 22 keys and in the key.each loop you are binding the handlers again and again So it executes 22 times. Which means each of your keys have the same event registered 22 times. So consider the reciprocal situation that you have. You are taking the value from the textbox and converting it into its reciprocal so that is one time, and you are good. But it happens 22 times so even number of reciprocal operations on the same value returns the same value itself. Also you do not need to use eval. Just do the proper operation. Also do remember that javascript performs floating point arithmetic operation.

  key.each(function () {


        if (!$(this).is(functions)) {
            $(this).on("click", function () {
                var number = $(this).text();
                // Inserts value of clicked button into the input
                textBox.val(textBox.val() + number);
            });
        }
    }); //<-- end it here

    var clear = $(".row li.clear"),
        backspace = $(".row li.back"),
        equals = $(".row li.equals"),
        inverse = $(".row li.inverse");
    clear.on("click", function () {
        // Clears the input value if the clear button is clicked
        textBox.val('');
    });
    backspace.on("click", function () {
        // Removes last character of input
    });
    equals.on("click", function () {
        $("#function").text(textBox.val());
        // Evaluates what is in the input
        setTimeout(function () {
            // Sets that to the value
            textBox.val(eval(textBox.val()));
        }, 1);
    });

    inverse.on("click", function () {
        var val = textBox.val(),
            text = parseFloat(val),
            recip = eval(1 / text);
        textBox.val(recip);
    });
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top