-1

Thats it, how can I sum, some div class ID's when checkbox:checked with jquery?

Everytime I check a checkbox, I should be able to sum some ID's that came from some query that are related to each checkbox.

Eg. for 3 checked chekbox's

for every each checkbox:checked -> sum += $(".someclass").attr('id') 

My problem is: .attr(id) that save only the 1st found ID.

Imagine that first ID = 5.

my sum will be 5+5+5, and not ID(class value from checkbox1)+ID(class value from checkbox2)+ID(class value from checkbox3)

How could I do it ?

Thanks.

user1148875
  • 449
  • 4
  • 11
  • 24
  • Is the value of the ID attribute only a number? This isn't valid HTML. See this question and answer http://stackoverflow.com/questions/70579/what-are-valid-values-for-the-id-attribute-in-html Instead you can use a data attribute like data-id="" which can contain any alphanumeric value you like. – Mark Sep 19 '12 at 00:52
  • Or are you trying to get the value of the checkbox with that id? if so what your selector would look like is `$('.someclass').val()` not `.attr("id")` – Mark Sep 19 '12 at 00:54
  • yes its only numbers. Im trying to get some id of some class when I trigger a checkbox, i dont want to sum the checkbox id itself, but something related to it – user1148875 Sep 19 '12 at 00:59

1 Answers1

2

Try with this

var sum = 0;
$(".someclass:checked").next().each(function(){
    sum += Number(this.id);
})

DEMO

This assume that "related" input is next to the checkbox. This is the example layout I used for my demo

<input type="checkbox" class="someclass" checked></input><input id="1"></input>
<input type="checkbox" class="someclass"></input><input id="2"></input>
<input type="checkbox" class="someclass"></input><input id="3"></input>
<input type="checkbox" class="someclass" checked></input><input id="7"></input>​
Claudio Redi
  • 67,454
  • 15
  • 130
  • 155
  • this works. But I have multiple checkboxs, how could I restrict that function only to checked:checkbox ? – user1148875 Sep 19 '12 at 00:55
  • .someclass:checked that return 0. Because .someclass its not the same class of my checkbox. Its hard to explain: What I need to be added is a value that came from a query and is related to the checkbox. I dont want to sum the checkbox ID itself – user1148875 Sep 19 '12 at 01:08
  • Every checked checkbox has an input field related to it. is that value that I need to get when a select a checkbox – user1148875 Sep 19 '12 at 01:10
  • how is related? Is it placed next to the checkbox? – Claudio Redi Sep 19 '12 at 01:16
  • near? you'll need to be more specific... I changed the example assuming that the input is exaclty next to the checkbox. – Claudio Redi Sep 19 '12 at 12:36