Skip to content Skip to sidebar Skip to footer

Dynamical Calculator Javascript

It is a calculator which has spans from which I want to take a values(1,2,3, etc.) and two fields: First for displaying what user is typing and the second is for result of calculat

Solution 1:

var keys = document.querySelectorAll(".keys span");

for (var i = 0; i < keys.length; i++) {
    keys[i].onclick = function(){
        alert(this.innerHTML);
    }
}

keys is a NodeList so you cannot attach the onclick on that. You need to attach it to each element in that list by doing the loop. To get the value you can then simple use this.innerHTML.

Fiddle

Solution 2:

This should get you started.. you need to get the value of the span you are clicking and then append it into your result field. Lots more to get this calculator to work but this should get you pointed in the right direction.

Fiddle Update: http://jsfiddle.net/vb394983/3/

JavaScript (jQuery):

$(".keys").on("click","span",function(){
    var clickedVal = $(this).text();
    $(".display.result").append(clickedVal);
});

Solution 3:

You can set a click event on the span elements if you use JQuery. Eg:

$("span").click(
    function(){
        $("#calc").val($("#calc").val() + $(this).text());
    });

See: http://jsfiddle.net/vb394983/6/

That's just to answer your question but you should really give the numbers a class such as "valueSpan" and the operators a class such as "operatorSpan" and apply the events based on these classes so that the buttons behave as you'd expect a calculator to.

Solution 4:

http://jsfiddle.net/vb394983/7/

var v="",
   max_length=8,
   register=document.getElementById("register");
   // attach key events for numbers   var keys = document.querySelectorAll(".keys span");
   for (var i = 0; l = keys.length, i < l; i++) {
       keys[i].onclick = function(){
            cal(this);
       } 
   };
   // magic display number and decimal, this formats like a cash register, modify for your own needs.
   cal = function(e){

        if (v.length === self.max_length) return;
        v += e.innerHTML;
        register.innerHTML = (parseInt(v) / 100).toFixed(2);

   }

Solution 5:

Using JQuery will make your life much easier:

$('.keys span').click(function() {
    alert(this.innerHTML);
});

Post a Comment for "Dynamical Calculator Javascript"