Reputation: 5670
I am trying to select certain checkboxes (think of a select all checkbox that checks other boxes). I am succesfully "checking" them but don't want to do them all. Consider the following screenshot:
Here is the jQuery. It is selecting every single checkbox when I need it to only select the checkboxes in that group. Since this ASP.NET is dynamic I have very little control over the HTML so I need to find and select what I need in the DOM as the objects appear. In other words, I can't add class names, id's, etc.
$(".anAlarmGroup input:first-child").click(function () {
if ($(this).is(":checked")) {
//Select all alarms following this group heading until reaching the next group heading, while also grabbing each alarm ID
$('.anAlarm').find('input[type="checkbox"]').attr('checked', 'checked');
}
else {
$('.anAlarm').find('input[type="checkbox"]').removeAttr('checked');
}
});
Upvotes: 0
Views: 280
Reputation: 38365
If you are generating the page dynamically, you can add class like so. I created this method because I often add multiple css classes and wanted to simplify that. So you just call AddCssClass(someControl,"anAlarmGroup")
public static void AddCssClass(WebControl control,string cssClass)
{
if (!control.CssClass.Contains(cssClass))
{
control.CssClass += (control.CssClass == String.Empty ? "" : " ") + cssClass;
}
}
Note that it will fail to add a css class if it is a sub string of another class such as adding "bold" if "bolditalic" already exists.
Upvotes: 0
Reputation: 92893
$('.anAlarm').find('input:checkbox[name="whatever"]').prop('checked', true);
Or, in your case:
$(".anAlarmGroup input:first-child").click(function () {
$('.anAlarm')
.find('input:checkbox[name="'+$(this).attr('name')+'"]')
.prop('checked', ($(this).is(':checked')));
});
That should only check (or uncheck) the checkboxes with the same name.
Upvotes: 1
Reputation: 11
Inside your click handler function you could use $(this).siblings('input[type="checkbox"]').attr('checked', 'checked');
or $(this).parent().find('input[type="checkbox"]').attr('checked', 'checked');
depending how they are grouped. That will only look for elements at similar or deeper levels in the DOM.
Upvotes: 0
Reputation: 12935
Without seeing your code it's difficult to come up with a surefire solution, however with JQuery you can use CSS style selectors to select DOM elements. You can use this to your advantage and select, for instance, only inputs that are a child of that particular fieldset if that fieldset has a unique class or ID. Or, if the fieldset doesn't have a unique ID you could select it bast on the :first-child selector of the form itself.
Upvotes: 0