0

I am trying to push all select elements starting with specific id or name and tried the following but it doesn't seem to work:

var IDs = [];
$("#dynamic_field [id^='product_id']").find("select").each(function(){ IDs.push(this.id); });
alert(IDs.length);

If I don't specify the specific select id or name it works:

var IDs = [];
$("#dynamic_field").find("select").each(function(){ IDs.push(this.id); });
    alert(IDs.length);

Any help please.

Just_Do_It
  • 821
  • 7
  • 20

1 Answers1

3

You are trying to get select tag within select tag, remove the find part since its already contains collection of select tags(assuming elements with id prefix product_id are select tags). If there are other elements with id prefix product_id then combine select with the attribute starts with selector.

var IDs = [];
$("#dynamic_field select[id^='product_id']").each(function(){ IDs.push(this.id); });
alert(IDs.length);


You can use jQuery map() method to generate the array where use get() method to convert jQuery collection to array.
var IDs = $("#dynamic_field select[id^='product_id']").map(function(){ return this.id; }).get();

or using jQuery.map method.

var IDs = $.map($("#dynamic_field select[id^='product_id']"), ele => ele.id);
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188