How can I add values to a div based on the checked values in a list?

Take a look at this screenshot...

screenshot
What I need to do is create a script that goes through all of the checked articles and write the titles of those checked articles into a div and then go back and see how many articles were selected and apply the appropriate discount.

I've seen this done.

What I'm envisioning is a button at the bottom that "totals" all of the checkboxes with a for loop and looks to see which ones have been checked. But after that, I'm lost. How do I create an array or some sort of dynamic that can be appended and then make a calculation based on that appended list?

JQuery or Javascript....

Thanks so much!
Bruce GustPHP DeveloperAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Leonidas DosasCommented:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-latest.min.js"></script>
<title>HTML, CSS and JavaScript demo</title>
</head>
<body>
<!-- Start your code here -->

<input type="checkbox" />
<p>One</p>
<input type="checkbox" />
<p>Two</p>
<input type="checkbox" />
<p>Three</p>
<button id="myButton">Click</button>
<!-- End your code here -->
  
  <script>
   var myDiv=$('<div></div>');

$('#myButton').on('click',function(){
  $(':checkbox').each(function(){
  if($(this).is(':checked')){
    var a=$(this).next('p');
    console.log(a);
    myDiv.append(a[0]);
  }
  
});
  $('body').append(myDiv);
});
    
  </script>
</body>
</html>

Open in new window

0
Slick812Commented:
greetings brucegust, , , I read what you said in question, but I am not sure what you say a problem is by -

     "ones have been checked. But after that, I'm lost. How do I create an array or some sort of dynamic that can be appended and then make a calculation based on that appended list"

I do not see a problem, as If you get the "Article" title from each checked (in an array) then write titles (from array)  to  the Order <div>, then you already have a count of articles in the length of the array.

OR

If you just detect the checked an write the title to div, then you can just have a counter variable to add all that were ordered?

Here some code that works in firefox -
<!DOCTYPE html>
<html lang=en><head>
<title>Get Checks and ADD</title>
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=yes" />
<style>
body{background:#fed;}

#avail1 {
font-family: serif;
width: 48em;
padding: 5px;
border: 1px dotted #00b;
}

#avail1 input {
background: #99d;
margin-right:25px;
margin-bottom: 38px;
vertical-align: top;
}

#avail1 span {
display: inline-block;
width: 33em;
vertical-align: top;
}

#avail1 button {
margin: 7px 42px;
vertical-align: top;
}

#ordered {
margin-top:3px;
width: 48em;
padding: 5px;
border: 1px dotted #b00;
}
</style>
</head>
<body>
<h3>Get Checks and ADD</h3>
Order Online by Checking the Article below<br />
$10.00 per Article or $25.00 for Three, or $60.00 for all Nine Articles.
<p id="avail1">
<input type="checkbox" /><span>1 Developmental Article Fill More Fill More Fill More Fill More Fill More Fill More Fill More - Vol 5 Number 2, pages 3-7</span><br />
<input type="checkbox" /><span>2 Developmental Article Fill More Fill More Fill More Fill More Fill More Fill More Fill More - Vol 5 Number 2, pages 3-7</span><br />
<input type="checkbox" /><span>3 Developmental Article Fill More Fill More Fill More Fill More Fill More Fill More Fill More - Vol 5 Number 2, pages 3-7</span><br />
<input type="checkbox" /><span>4 Developmental Article Fill More Fill More Fill More Fill More Fill More Fill More Fill More - Vol 5 Number 2, pages 3-7</span><br />
<input type="checkbox" /><span>5 Developmental Article Fill More Fill More Fill More Fill More Fill More Fill More Fill More - Vol 5 Number 2, pages 3-7</span><br />
<input type="checkbox" /><span>6 Developmental Article Fill More Fill More Fill More Fill More Fill More Fill More Fill More - Vol 5 Number 2, pages 3-7</span><br />
<input type="checkbox" /><span>7 Developmental Article Fill More Fill More Fill More Fill More Fill More Fill More Fill More - Vol 5 Number 2, pages 3-7</span><br />
<input type="checkbox" /><span>8 Developmental Article Fill More Fill More Fill More Fill More Fill More Fill More Fill More - Vol 5 Number 2, pages 3-7</span><br />
<input type="checkbox" /><span>9 Developmental Article Fill More Fill More Fill More Fill More Fill More Fill More Fill More - Vol 5 Number 2, pages 3-7</span><br />
<button>ORDER All Articles Checked !</button>
</p>
Cart-
<p id="ordered">
- - -
</p>
<script>
function id2ob(elmtID){return document.getElementById(elmtID);}
id2ob("avail1").getElementsByTagName("button")[0].onclick = function() {//alert("Button Click");
var cks = id2ob("avail1").getElementsByTagName("input"),sns = id2ob("avail1").getElementsByTagName("span"),cart=[],cost=0,out1='';
for (var c=0;c<cks.length;++c) {
  if(cks[c].checked) {cart.push(sns[c].innerHTML.substr(0, 23));}
  }
if(!cart.length){alert("No Items Checked, NO ORDER"); return}
switch(cart.length) {
  case 9: cost=60; break;
  case 8: cost=70; break;
  case 7: cost=60; break;
  case 6: cost=50; break;
  case 5: cost=45; break;
  case 4: cost=35; break;
  case 3: cost=25; break;
  case 2: cost=20; break;
  case 1: cost=10; break;
  default: cost=0;
  }
if(!cost){alert("No Items Checked, NO ORDER"); return}
out1 += "<b>Your Total Cost for "+cart.length+" Articles is $"+cost+".00</b><br />Articles Ordered -<p>";
for (c=0;c<cart.length;++c) out1 +=cart[c]+"<br />";
id2ob("ordered").innerHTML = out1;
}
</script></body></html>

Open in new window


I did a switch to determine the cost, but you can do the total cost by math, divide number orderd by 3,  and multiply that by 25.00 and then multiply the remainder (of t/3) by 10.00.
0
Bruce GustPHP DeveloperAuthor Commented:
Slick!

What you've recommended is exactly what I need. But rather than cut and paste, let me try to deconstruct what you've done so I can learn what you've done and not just mimic it.

I'm seeing some of it, but there's parts where I'm not connecting the dots.

Your functionality is initiated with a button that's within the <p id="avail1"> paragraph:

id2ob("avail1").getElementsByTag name("button")[0].onclick=function()

But what's "id2ob?" It looks as though you've got a function within a function. How's that playing out? And I don't see where the [0] is coming from. I can see that it will prove handy when you start looping through your <span>'s, but you've got one button. How can you assert an array-esque dynamic onto to a solitary element?

You then set up a var called "cks." I can see where those "looped" values will be coming from in light of you're grabbing all of the "inputs" within the "avail1" id.

What's "sns?" I tried to google that, but I ran into some amazon dynamics and I figured I would just ask Slick.

Hou set up your cart as an empty array, you set up your cost as an integer with a value of 0 and your out1 variable as a string.

You then kick off your for loop for the number of checked boxes. For every checked boxy, you're "pushing" the string connected to each <span> into the cart array.

You're then using the switch you set you to calculate the cost based on the "length" of the cart.

You wrap it up by assigning the the total cost verbiage and value to the "out1" value and then somehow add the titles to the "out1" variable, but I don't see how that's happening.

Could you please explain "sns" and how that's being used to facilitate the above magic?

Thanks!

Also, in the end, I've got to take the selected articles and pass the titles and the cost into two hidden fields that will be processed by a third party shopping cart dynamic. One field will be each of the titles separated by a comma and the other field will be the combined cost based on the number of articles selected. I've got that as a separate question at: https://www.experts-exchange.com/questions/29075354/How-can-I-take-the-selected-values-and-insert-them-into-two-separate-text-fields.html

Thanks!
0
Big Business Goals? Which KPIs Will Help You

The most successful MSPs rely on metrics – known as key performance indicators (KPIs) – for making informed decisions that help their businesses thrive, rather than just survive. This eBook provides an overview of the most important KPIs used by top MSPs.

Slick812Commented:
ok, , , Before I try and step you through my code progression, I will tell some about what your question had me consider. First you have "Products" to choose by checks, and u want a button to show what was checked and a price to buy the list. I immediately thought of the online shopping CART to hold the products picked, their serial number, their quantity, and their price per item. Since for these there is no quantity , serial number, and all have the same price, I made a cart Array, that only had ONE element per ITEM, the description, from some element beside the check-box., since all items were the same price, I just just added an item to the cart (a string from a span),  IF the check was CHECKED, by this if test -    if(cks[c].checked)    - in this line -
         if(cks[c].checked) { cart.push(sns[c].innerHTML.substr(0, 23)); }
so the cart will have the number of  PDF ordered, so if the cart had 2 PDF in it, the cost wound be 20 bucks.

Now to my code, you ask - " But what's "id2ob?" " - I detest writing the long    document.getElementByID( )   over and over again in code, so I include a "Short Code Write" function at first -
         function   id2ob    (elmtID) { return document.getElementById(elmtID); }
this function HAS NO functioning except to save me much time in long code writes, so I can write -
    var a = id2ob("avail1");
instead of
    var a = document.getElementById("avail1");

Now, , I write alot of code all day long, so I have my code writing habits, and in javascript I use short-code syntax writing, I was not thinking when I wrote this code here, and just pounded it out as I usually do, so I shortened a code to

        id2ob("avail1").getElementsByTag name("button")[0].onclick=function() {}

I will do a break down into long code here -
// need to get the button container <p id="avail1">  first
  var buttonContainer = document.getElementById("avail1");
// now get an array with all of the "button" tags in it
  var buttons = buttonContainer.getElementsByTag name("button");
// since buttons is an Array and I just need ONE button I use the array [0] for onclick
  buttons[0].onclick = function() {
      this.innerHTML = "Clicked";
      }

Open in new window

so that code for me is shortened -
// long code -
  var buttonContainer = document.getElementById("avail1");
  var buttons = buttonContainer.getElementsByTag name("button");
  buttons[0].onclick = function() {
      this.innerHTML = "Clicked";
      }


// short code -
  id2ob("avail1").getElementsByTagName("button")[0].onclick = function() { this.innerHTML = "Clicked"; }

Open in new window


Next you ask -     What's "sns?"    - the sns is just a variable Name that I shorten spans to sns and is used in this code -
    var sns = id2ob("avail1").getElementsByTagName("span");

since I have exactly the same number of <span> in the container paragraph as I do <input>, then when I run a FOR LOOP for the checks  (inputs) I can use the same FOR LOOP runner var c in both the span and input -
      cks[c]     sns[c]

You ask -  "somehow add the titles to the "out1" variable, but I don't see how that's happening."

I use a FOR LOOP for the cart variable Array        for (c=0;c<cart.length;++c)        , and just ADD the cart string to the out1 string variable and place a line break <br /> as        out1 += cart[c]+"<br />";         to make a list -
     for (c=0;c<cart.length;++c) out1 +=cart[c]+"<br />";

Like I said, I just used my own code write conventions, and I know from others commenets that this way may not be understandable to many.

I hope this helps you, but I know that many now use Jquery or Prototype javascript libraries, and don't bother to learn much raw javascript.
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Bruce GustPHP DeveloperAuthor Commented:
Slick, I'm just now looking at your explanation after having spent some time looking over your solution again and it's validating to see some of what I was able to figure out reinforced by you having broken things down.

Thanks for taking the time to be so thorough. This is what makes this service such a valuable / crucial part of my developer's tool box!

Hope you had a great holiday.

Thanks again!
0
Slick812Commented:
thanks for the points, and I try and show people HOW do do things here at EE so I don't see so many of the "same old, same old" questions.

I looked at your other question about the hidden Form inputs, and  The code by  Leonidas Dosas  in comment  ID: 42415050 looks like it should work and add hiddens to a form.

Just to say, that I used a very very Simple element arrangement for my check inputs and span descriptions, to keep things short, BUT this may be difficult to make it width Responsive. Also there are a thousand very different layouts to get your checks and descriptions displayed, and the script code to run the checks and get the descriptions in those would probably be be very different.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
JavaScript

From novice to tech pro — start learning today.