MeteorShower
MeteorShower

Reputation: 113

Get checkbox values without Id JQuery

I am iterating through a dynamically created table which has rows that contain plain text, checkboxes, and select drop down boxes. While iterating through the table with

$('#myTableId td').each ->
  thisSelect = $(this).find("option:selected").text()
  if thisSelectBox != ""
    allSelectValues.splice selectCounter,0, thisSelectBox
    selectCounter++

So this code works to get my select values, and I am using a similar approach for the text boxes. My issue though is getting the checkbox values. Since the table is dynamically created, I cant get the checkbox values by id since the table is dynamically created and when I try to use this code:

$('#tableId td').each ->
   thisCheckbox = $(this).find("input.classNameOfCheckbox:checkbox").val()

It returns "on" when iterating on a td that contains a checkbox whether or not it was checked. So my question is what is the best approach for this problem?

Upvotes: 0

Views: 1089

Answers (1)

Patrick Evans
Patrick Evans

Reputation: 42746

Just add :checked to the end of your selector and it will only select those elements that are checked/selected

$(this).find("input.classNameOfCheckbox:checkbox:checked").val()

If none are checked, you will get undefined.

And if there is more than one checkbox checked in the td .val() will return only the first one's value. You would need to use .each or similar looping method to get each value

Demo

jQuery(document.body).append(      
  "Checked: "+jQuery("div").find("input:checkbox:checked").val() 
);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <input type="checkbox" value="first" />
  <input type="checkbox" value="second" checked />
  <input type="checkbox" value="third" />
</div>

Upvotes: 1

Related Questions