John
John

Reputation: 21927

Check Checkboxes loaded from JQuery Load

I am loading a set of checkboxes into a div using Jquery and the load function. My code is

$("#cb-list").load('www.someurl.com');

where www.someurl.com returns html for a bunch of checkboxes e.g.

<input type="checkbox" value="sddfdsf" name="cb[]" id="a1" />
<input type="checkbox" value="sddfdsf" name="cb[]" id="b2" />

I want to go through the checkboxes that have been returned and then check some of them based on parameters (I want to do this on the page that loads the checkboxes and not the page which is being loaded).

How would I go about this using jQuery? So for example I might have 3 checkboxes returned with IDs a1, b2, c3 and I would like to check b2 and c3. I would normally do

$("#b2").attr("checked") = 'checked';
$("#c3").attr("checked") = 'checked';

But this does not work and I am assuming this is because the checkboxes are being loaded from an external link.

Thanks

Upvotes: 3

Views: 3136

Answers (2)

Mutation Person
Mutation Person

Reputation: 30500

Assuming your AJAX call returns a string with the HTML you posted above, then you'll need to load that string into a jQuery variable:

//put html into a string
var myCheckboxes = $("#cb-list").load('www.someurl.com');
/*... possibly perform some validations here ... */
var $myCheckboxes = $(myCheckboxes);

Then set to checked individually:

$myCheckboxes.filter("#b2").attr('checked', true);
$myCheckboxes.filter("#c3").attr('checked', true);

Or set all using .each():

$myCheckboxes.each(function(){
    $(this).attr('checked', true);
});

I guess then you'll want to append it to something. Here we append to to a div with id ='MyDiv'

$myCheckboxes.appendTo("#MyDiv");

Upvotes: 4

antpaw
antpaw

Reputation: 15985

it should be $("#b2").attr('checked', true);

Upvotes: 3

Related Questions