0

I want to create a JS function to capture the 'value' attributes on each li element within the 'completed-tasks' unordered list. I also want it to add these values together.

My html:

<ul id="completed-tasks">
    <li value="1"><label>item 1</label></li>
    <li value="2"><label>item 2</label></li>
    <li value="3"><label>item 3</label></li>
</ul>

My javascript function:

var totalValue = function(){
    //cycle over ul items
    for (var i=0; i<completedTasksHolder.children.length; i++){
    //I want to capture 'value' of each li here
    }   
    //I want to add values here
}

Please help me finish that function ^^ (I know the loop is working). totalValue should be 6.

Ty M
  • 184
  • 1
  • 11

2 Answers2

0

Try this:

var totalValue = function () {
    //cycle over ul items
    var completedTasksHolder = document.getElementById("completed-tasks");
    var total = 0;
    for (var i = 0; i < completedTasksHolder.children.length; i++) {
        //I want to capture 'value' of each li here
        var v = parseInt(completedTasksHolder.children[i].getAttribute("value")); //parseInt for string to number conversion
        total += v;
    }
    //I want to add values here
    console.log(total);
}
totalValue();

Demo :http://jsfiddle.net/GCu2D/589/

K K
  • 17,794
  • 4
  • 30
  • 39
  • 1
    That 'parseInt for string to number conversion' line is exactly what I was looking for. Thanks! – Ty M Mar 01 '15 at 04:11
0

This will accomplish what you're looking for. It assumes that the value will always be convertible to a number (will result in NaN if any aren't).

function total() {
  var completedTasks = document.getElementById('completed-tasks'),
    total = 0;

  for (var i = 0; i < completedTasks.children.length; i++) {
    total += +completedTasks.children[i].value;
  }
  return total;
}

console.log(total());
<ul id="completed-tasks">
  <li value="1">
    <label>item 1</label>
  </li>
  <li value="2">
    <label>item 2</label>
  </li>
  <li value="3">
    <label>item 3</label>
  </li>
</ul>
jdphenix
  • 15,022
  • 3
  • 41
  • 74
  • thanks! I'm new to JS, how is using .value different than using .getAttribute("value")? – Ty M Mar 01 '15 at 04:26
  • @TyRoderick This explains it http://stackoverflow.com/questions/11973678/difference-between-element-value-and-element-getattributevalue – jdphenix Mar 01 '15 at 04:45