Tyrel Denison
Tyrel Denison

Reputation: 476

How do I count the number of select lists with selected values using JQuery?

I am creating the mobile version on a current Rails app with a "quiz" feature. There is currently a count of how many questions you have answered being generated by this function.

function updateGroupProgressCounter($group){
 var count = $group.find('tr').has('input:checked').length;
 $group.parents('.carousel').find('.checkedCount').text( count);
}

I am changing the inputs from radio buttons to select boxes for mobile and want to keep the count feature but can't quite make it work so far. I've tried

var count = $group.find('tr').has('select option:selected').length;

but gives me the total number of questions in that group. Any help is appreciated.

Upvotes: 0

Views: 137

Answers (3)

charlietfl
charlietfl

Reputation: 171669

I would toggle a class on the row based on select change event, then count those rows.

$('tr select').change(function(){
   $(this).closest('tr').toggleClass('answered', $(this).val()!='' );
});

Second argument of toggleClass determines whether to add/remove.

Then to get total rows:

$('tr.answered').length

toggleClass() API Docs

Another approach using filter() to count select that have value

var number_answered=$('tr select').filter(function(){
      return $(this).val !='';
}).length

Upvotes: 2

Ranjit Singh
Ranjit Singh

Reputation: 3735

Considering the value of first element of your select list is empty(i.e "")

So the code will be

var count = 0;
$group.find('tr select').each(function(){
   if(this.value.length)
     count++;
});

I know this is not the best way to do it. Adding and removing class on the basis of selection and finally finding the length of element that contains required class would be better approach as suggested by @charlietfl.

Upvotes: 0

Thomas Junk
Thomas Junk

Reputation: 5676

Probably you are looking for something like this:

$("#boxes").on("change","input", function(){
    $("#total").val($("#boxes input:checked").length);  
});

Play around with the fiddle

Upvotes: 0

Related Questions