I don't think I explained myself as best I could last time, so I'm going to give it another shot. From the following code:
<div id="addons" class="grid_12 omega">
<div class="addon">
<span><input type="checkbox" name="addon_1" value="addon_1"></span>
<span class="title">Title 1 here</span>
<span class="cost">$<em>49</em></span>
<p>Some text here</p>
</div>
<div class="addon">
<span><input type="checkbox" name="addon_2" value="addon_2"></span>
<span class="title">Title 2 here also</span>
<span class="cost">$<em>95</em></span>
<p>Some more text.</p>
</div>
<div id="summaries" class="hidden">
<input type="button" id="totalme" name="totalme">
<input type="text" value="" id="addons_titles" name="addons_titles"><!-- item titles array, from addons that are checked -->
<input type="text" value="" id="addons_cost" name="addons_cost"><!-- total cost, from addons that are checked -->
</div>
</div>
For all "input[type=checkb开发者_JAVA技巧ox][checked]" (checked addons), I'm trying to:
- summarise the titles from ".addon .title input[name]" to input#addons_titles (each title separated by pipe characters - eg: "Item 1 title | Item 2 title")
- and total item costs from ".addon .cost em" to input#addons_cost
I think the code given previously by Obalix and Nick Craver are on the mark, I'm just not sure how to edit it to only do it for selected addons.
Also I'm not sure how to trigger this. I'm assuming I should run this on a submit button so the array is only created once - otherwise titles could be continually added to an ever duplicated array?
Appreciate your thoughts.
I think your question is more clear now.
This will work for your requirements:
$('#totalme').click(function () {
var items = $('input:checkbox:checked'), // checked elements
titles = [], // store the selected titles
totalCost = 0; // store the total cost
items.each(function () { // iterate over the checked elements
var addon = $(this).closest('div.addon'), // get the closest div.addon
title = $('span.title', addon).text(), // get title
cost = +$('span.cost em', addon).text(); // get cost coerced to number
titles.push(title); // add the title
totalCost += cost; // add the cost to sumarize
});
$('#addons_titles').val(titles.join('|'));//join all titles with | as separator
$('#addons_cost').val(totalCost); // show the amout
});
Check a live example here.
精彩评论