I'm trying to do some jquery addition on appended items and I'm wondering if this is a good idea and how to achieve it.
Scenario:
I'm generating a table of ingredients that can be added to an item.
<ul id="greens" class="card-content-ingredients" style="list-style-type: none;">
<?php foreach ( $greens as $grn ): ?>
<li value="<?php echo $grn['price']; ?>" id="<?php echo $grn['id']; ?>" cal="<?php echo $grn['nutritionix_cal']; ?>">
<input type="hidden" class="item_id" value="<?php echo $grn['id']; ?>" name="greens" />
<span class="item-name-small"><?php echo $grn['name']; ?></span>
<span class="item-description-menu"><?php echo $grn['description']; ?></span>
<span class="content-right"></span>
</li>
<?php endforeach; ?>
</ul>
Whenever a customer clicks on one of the items, I append the item to another div and perform an AJAX call for server-side manipulation:
<script> <!-- Appending the DIV -->
$(function (){
$('ul.card-content-ingredients li').click(function(){
$('#scroll-2 ul').append($(this));
})
});
</script>
<script> <!-- AJAX -->
$(document).ready(function(){
$('ul.card-content-ingredients li').click(function(){
var id = $(this).attr('id');
var value = $(this).attr('value');
var cal= $(this).attr('cal');
$.ajax({
url: "add-to-cart.php",
type: "POST",
dataType: "json",
data: {'id' : id, 'value' : value, 'cal' : cal },
success: function() {}
});
});
});
</script>
What i'm wondering, is that during the appending step, is there a way for me to perform addition on an input variable?
If my DIV was written as such:
<div class="pure-u-1 pure-u-md-3-5 pure-u-lg-3-5 content-left">
<div id="scroll-2" class="card">
<span class="is-center">
<?php echo substr($menu_item['name'], 0, -6); ?><br />
<?php echo CURRENCY . $menu_item['price'] . " - Cal: " . $menu_item['nutritionix_cal']; ?>
</span>
<ul style="list-style-type: none;">
</ul>
<input id="calories" type="text" value="0" size="1" name="calories" disabled>
</div> <!-- END CARD -->
</div> <!-- END RIGHT SIDE DISPLAY -->
So when the element is appended to the div from the left side to the right side, how can I perform addition to add the cal
attribute to my input box for Calories
?
Currently, I am returning the value after PHP retrieves all values and processes the addition of cost and caloric information but with append it would be quicker for the initial response, making the website "seem" quicker.
Is this a fool's errand?
you can do something like
var totalcalories;
$("[name='calories']").each(function(){
totalcalories = totalcalories + $(this).val();
});
in your success function of ajax, so your ajax function would update to
var totalcalories;
$.ajax({
url: "add-to-cart.php",
type: "POST",
dataType: "json",
data: {'id' : id, 'value' : value, 'cal' : cal },
success: function() {
$("[name='calories']").each(function(){
totalcalories = totalcalories + $(this).val();
});
}
});