test
test

Reputation: 23

javascript find control id

I have checkboxes generated with an auto ID

I am using the function below:

getAllSelectedFeeds = function() {
 var val = []; 
 $('input:checkbox:checked').each(function(i) {
   val[i] = $(this).attr('id');
 });
 return val;
};

It checks if any checkboxes are checked but I only want it to run for those checkbox controls with "selectedTask" within their autogenerated id such as id="ctl00_m_g_95e8bffc_8200_46ac_887c_98522e26803c_ctl01_ctl02_selectedTask

Would this javascript work (using jquery selector) by selecting only those checkboxes checked within a div called 'feedSelector'? //Get selected checkboxes IDs

getAllSelectedFeeds = function() {
 var val = []; 
 $('#feedSelector:input:checkbox:checked').each(function(i) {
  val[i] = $(this).attr('id');
 });
 return val;
};

Upvotes: 1

Views: 2204

Answers (2)

mck89
mck89

Reputation: 19231

getAllSelectedFeeds = function() {
 var val = []; 
 $('input:checkbox:checked[id*=selectedTask]').each(function(i) {
   val[i] = $(this).attr('id');
 });
 return val;
};

With this you get every checked checkbox with an id that contains "selectedTask"

Upvotes: 0

Parrots
Parrots

Reputation: 26882

getAllSelectedFeeds = function() {
 var val = []; 
 $('input:checkbox:checked[id*=selectedTask]').each(function(i) {
   val[i] = $(this).attr('id');
 });
 return val;
};

(if it always ends with "selectedTask" you can use $= instead of *=)

Although I'd really recommend avoiding doing it like this as it has to search every ID for that string, which is inefficient. Might want to add a class to the checkboxes so you can just query on that because it'll be a lot faster, especially if you start to get a lot of checkboxes:

getAllSelectedFeeds = function() {
 var val = []; 
 $('input.selectedTask:checked').each(function(i) {
   val[i] = $(this).attr('id');
 });
 return val;
};

Upvotes: 3

Related Questions