Nevershow2016 Nevershow2016 - 2 years ago 65
Javascript Question

Javascript, cant subtract values

Hi guys so basically i am trying to add data in a nutrtion label which i built. So the label it self has everything from fat, carbs , protein etc. Now i have set up a database with:

ingName: ....
fat: ...
carbs ... etc

So right now i am just trying to get it to work for fat. Once i do this i can easily do the others. I can search through the database easily.When the user presses Add button it will add the ingredient below the search box and then change the content of fat. However i am having a major problems with it right now.

When the user clicks on the red cross to delete the element i want it to subtract the fat of the label. So if the user adds an apple with 1 fat and then adds banana with 4 fat. Then the user decides to delete the apple it should go back to 4 fat from 5 fat.

Answer Source

You appear to be storing the new fat counter in each new span, so if you add apples worth 5 then you make a span with data of 5, then you add that to your current_fat counter and the next time you add another item the data of that item is now accumulative. I have created some of the code in this fiddle. It seems to be working the way you describe now.

I know what I am saying may be confusing, so look at the fiddle.

  • If you add apples worth 5
  • Then add bananas worth 5
  • Then add green beans worth 5

You are taking the 5 from the apples and putting those 5 points into this variable called current_fat then you add the point value for the bananas and then the point value for the green beans so what you end up with is a span with apples at 5, bananas at 10, and green beans at 15, so when you remove green beans all of your fat is dropping to zero, instead you need to take each item with it's own point value into the span.

var current_fat = 0;

$('#addButton').on('click', function(event) {
  if ($('#search_term').val() == '') {
    alert('please fill something in text box');
  } else {
    var searchedValue = $('#search_term').val();
    temp = $("#fat").text();
    temp = parseInt(temp);

    temp = $("#fat").text();
    temp = parseInt(temp);

    current_fat += temp;

    var divHolder = $('.selectedStuff');
    $("<div>" + searchedValue + "<span data-fat='" + temp + "'>X</span></div>").css({
      'background-color': 'yellow',
      'width': '700px',
      'margin-top': '10px',
      'border-style': 'solid',
      'border-color': '#0000ff'

  $('.selectedStuff span').on("click", function() {
    var fat = Number($(this).data('fat'));
    $('#fat').text(Number($('#fat').text()) - fat);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download