robboe
robboe

Reputation: 43

Jquery store string and put it out elsewhere when checkbox is checked

looking for some help here. I have to create a price check calculator. Two things need to be done:

  1. If checkboxes with different values are checked the overallprice has to be shown somewhere.
  2. I need a summary of all selected items. So i need to put the selected items beneath the overallprice.

I managed to get point 1 to work. But im struggling with point 2. I have no clue how to put the checked items elsewhere.

Heres how far ive got:

$(document).ready(function() {
 $('input[type="checkbox"]').click(function() {
   var total = 0;
   //var item = [];
   var $parent = $(this).closest('ul');
   $parent.find('input:checked').each(function() {
      total += parseInt($(this).val());
      //item.text();
   });
   $parent.find('span[class^=total]').html(total + ' €');

   var overallPrice = 0;
   $('span[class^=total]').each(function() {
     overallPrice += parseInt($(this).html().replace(' €',''));
   });
   $('.overallprice').html(overallPrice)
   //$('.overallprice').append(item);
   });
});

And for better understanding the JSFIDDLE

I'd be grateful for some help. Thanks alot!

Upvotes: 0

Views: 32

Answers (3)

frikinside
frikinside

Reputation: 1244

I provide a similar aproach like the previous questions but making sure you only get the item name and not the price for the sumary.

First, add this to you HTML:

<h4>Sumary:</h4>
<ul id="sumary">
</ul>

Then add this loop at the end of your checkbox click event:

//Sumary
    $("#sumary").html('');
    $('input:checked').each(function(){
      $("#sumary").append("<li>" + $(this).next("label").clone().find("span").remove().end().text() + "</li>");
    }); 

I fork your jsFiddle with the changes for demo.

Upvotes: 0

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67217

Try to use the following code,

What i did here is, Used the next sibling selector + for picking the relevant label element. And fetched its text and map it to an array, then displayed the result.

$('.overallprice').append($("<div>", {
  text: $("[type='checkbox']:checked + label").map(function() {
   return $(this).contents()[0].nodeValue;
  }).get()
}));

DEMO

Upvotes: 1

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167240

You need to loop through the checked boxes and get the label values:

  1. Get the checked check boxes and loop through them.
  2. for each one, get the label's text content that's next and append it.

Code

// get the checked check boxes
$("input:checked").each(function () {
    // for each one, get the label's text content that's next and append it.
    $('.overallprice').append("<br>" + $(this).next("label").text());
});

Fiddle: https://jsfiddle.net/truvrurc/

Upvotes: 0

Related Questions