Dynamically add object value to div inside <p> tag

Viewed 1831

On click of a button, I want to add a p tag to an existing div with the value of an object property name inside of it.

  var foodLoads = {
    orange: 6.7,
    apple: 5.6,
    banana: 12.7,
    grapes: 16.3,
    peach: 2.7,
    pear: 6.5,
    mango: 16.1,
    blueberries: 9.3,
    grapefruit: 1.7,
    strawberry: 3.5,
    tangerine: 3.1,
    watermelon: 8,
    duck: 0,
    beef: 0,
    chicken: 0,
    ham: 0,
    turkey: 0,
    elk: 0,
    pork: 0,
    fish: 0,
    eggs: 0,
    lamb: 0,
    applejuice: 11.8,
    cranberryjuice: 23.3,
    orangejuice: 14.4,
    carrotjuice: 8.6,
    lemonade: 24.3,
    hotchocolatemix: 10.2,
    tomatojuice: 3.5,
    chocolatemilk: 13.3,
    almondmilk: 0.02,
    soymilk: 4,
    wholewheatbread: 6.1,
    whitebread: 10.7,
    bagel: 30,
    waffle: 13.8,
    pancake: 5.3,
    croissant: 12.2,
    muffin: 28.8,
    englishmuffin: 21.3,
    doughnut: 15.2,
    oatmeal: 12.6,
    quinoa: 20.4,
    wholegrainbread: 7.1 
  }

The divs are created dynamically when a user checks a checkbox (this is before they click the button).

  $('input').on('ifChecked', function(event) {       
    var liText = $(this).parent().parent().text();
    var wrappedUp = $('<div class="active"><li>' + liText + '</li><select class="serving-size"><option value="1">1</option><option value="2">2</option><option value="3">3</option><option value="4">4</option></select></div>');
    $('.food-list').append(wrappedUp);
    $(wrappedUp).addClass('' + liText + '');        
})

This is an example of the divs I'm talking about

<ul class="food-list">

    <div class="active Mango">
                 <li>Mango</li>
          <select class="serving-size"><option value="1">1</option><optionvalue="2">2</option><option value="3">3</option><option value="4">4</option>
          </select>
    </div>
</ul>

So, basically, on click of a button I want to be able to use the class (i.e. Mango) to match it with the property in the foodLoads object with the same name (mango), put that property's value in a p tag, and add it to the div with the matching class (Mango).

This is the jQuery I was trying to use. As I am new to jQuery I'm sure the syntax is all screwed up.

  $('.submit-items').click(function() {
    $.each( foodLoads, function( key, value ) {
      if ($('.active:contains(' + key + ')')) {
        $(this).append('<p>' + key + '</li>');
      }
})

     })

Any ideas? Thanks in advance :)

1 Answers
Related