Reputation: 473
I would like all dropdown boxes in a div to have the same dynamic options
This works fine for one Dropdown list
var ddl = $("#ddl_candidate_id");
for (k = 0; k < fileDetails.Headers.length; k++) {
ddl.append("<option value='" + fileDetails.Headers[k] + "'>" + fileDetails.Headers[k] + "</option>");
but if I try and use a selector the code iterates through just as I expect it to but I guess
var dropdowns = $('.selectMapping');
is not strongly typed as a select (drop down)
var dropdowns = $('.selectMapping');
for (ov = 0; ov < fileDetails.Headers.length; ov++) {
for (dd = 0; dd < dropdowns.length; dd++) {
dropdowns[dd].append("<option value='" + fileDetails.Headers[ov] + "'>" + fileDetails.Headers[ov] + "</option>");
}
}
Thanks for your help.
Upvotes: 0
Views: 32
Reputation: 28621
There's no need to loop through a jquery collection as .append
will apply to all elements in the collection
var ddls = $(".select_class");
for (k = 0; k < fileDetails.Headers.length; k++) {
ddls.append("<option value='" + fileDetails.Headers[k] + "'>" + fileDetails.Headers[k] + "</option>");
}
var ddl = $("select");
for (k = 1; k < 10; k++) {
ddl.append("<option value='" + k + "'>" + k + "</option>");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select></select>
<select></select>
<select></select>
Regarding why your code was not working: Your issue is with dropdowns[dd].append(
as that is no longer a jquery collection. $("select")[0]
will give a DOM element.
You want .eq(dd)
instead of [dd]
then your dd loop will work.
var dropdowns = $('.selectMapping');
for (ov = 0; ov < fileDetails.Headers.length; ov++) {
for (dd = 0; dd < dropdowns.length; dd++) {
dropdowns.eq(dd).append("<option value='" + fileDetails.Headers[ov] + "'>" + fileDetails.Headers[ov] + "</option>");
}
}
as noted above, there's no need for this in this scenario, but it completes the issue raised in the question, this may be relevant for a different scenario
Upvotes: 2