Morpheus Morpheus - 5 months ago 34
jQuery Question

jquery calculator with editable field from array

Based on previous answer on another question, the next step is adding mini calculator...

for (var i = 0; i < animals.length; i++) {
output.push('<p>' + animals[i] + '<input class="pull-right" value="0" />' + '</p>');


JS Fiddle

I was trying to get value of input with jquery val() but without success...
Any other suggestion?

As you can see in jsfiddle list is like:

cat 0

dog 0

monkey 0

Total:

So if user updates cat to be 2 and dog to be 1, I would like to show 3 in total.

Thanks.

EDIT:
Link to previous questions

Answer

Please refer the fiddle

In the text box change event please add a function as below

$(".animals-input").change(function(e) {
  calculator();
});

function calculator()
{
  var result = parseInt(0);
  $(".animals-input").each(function(){
    result = result + parseInt($(this).val());
    $("#total-animals").html("Total:"+result);
  });
}

UPDATE

Inorder to reset the total dragging you need to add my calculator method in your droppable event.So your code would look like this

$(".animals-box").droppable({
    drop: function(event, ui) {
      if ($(".animals-box img").length == 0) {
        $(".animals-box").html("");
      }
      ui.draggable.addClass("dropped");
      var elem = ui.draggable[0].getAttribute('id').split('-')[1];
      animals.splice(animals.indexOf(elem), 1);
      var output = [];
      for (var i = 0; i < animals.length; i++) {
        output.push('<p>' + animals[i] + '<input class="pull-right" value="0" />' + '</p>');
      }
      $('#list').html(output.join(""));
      $(".animals-box").append(ui.draggable);
      $('#list').html(output.join(""));
      calculator(); // Add this method into your existing code you will get the result.
    }
  });
});

This is a sample Fiddle. Please check if it works for you

I hope this would help you.

Comments