I have code which displayed a person's info in a table(fields:name, surname, address, etc.) and one of the inputs is a checkbox. The code is as follows:

$("#table").append('<tr class="trow'+j+'">'+
                      '<td class="ids" id="z'+i+'">'+totrecs+'</td>'+
              '<td>'+member[i].jdate+'</td>'+
              '<td class="users" 

              '<td id="contact'+i+'">'+member[i].fname+' '+member[i].lname+'</td>'+
              '<td id="myaddress'+i+'">'+member[i].address1+' '+member[i].town+'</td>'+

              '<td><input type="checkbox" name="whome" id="showMe'+i+'"'+
                                             'class="boxes" onclick="getMe('+i+')" /></td></tr>');  
      totrecs++;
      j++;
     }

and the button -

<input type="button" id="selectall" title="Select All" value="Select All" />

What I am tryin to do is program a function that when clicking a certain button all of the checkboxes will be selected/checked.

I would appreciate any help. Thank You.

Dani AI

Generated

A short expert note tied to the replies by and : both answers set the checkbox state via the attribute, which will work in many cases but is not the modern, robust approach. For jQuery 1.6+ the checked state should be set on the DOM property (not the attribute), and programmatic changes do not automatically run click/inline handlers. The safest pattern is (1) set the property, (2) trigger the change event if other logic needs to run, and (3) prefer delegated event handlers instead of inline onclick so dynamically appended rows behave consistently.

Example — check all and let any change handlers run:

$("#selectall").on("click", function() {
  $(".boxes").prop("checked", true).trigger("change");
});

If a toggle is wanted (Select All / Deselect All) and the button text should reflect state:

$("#selectall").on("click", function() {
  var all = $(".boxes");
  var makeChecked = all.filter(":checked").length !== all.length;
  all.prop("checked", makeChecked).trigger("change");
  $(this).val(makeChecked ? "Deselect All" : "Select All");
});

Practical refinements: remove inline onclick="getMe(...)" and use a delegated change handler that reads a data-index (or the checkbox id) to call getMe — this keeps selection logic and row-handling logic separated and ensures newly appended rows are handled automatically. Ensure each checkbox id is unique, and for large datasets set the property on the whole collection (as above) rather than looping each element for better performance. For older jQuery (<1.6) .attr("checked", "checked") was common, but upgrading jQuery and using .prop() is recommended.

Recommended Answers

All 2 Replies

$(".boxes").each(function(){
    $(this).attr('checked', 'checked');
});

$(".boxes").attr("checked","checked");

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.