1

I am dynamically creating elements with javascript that end up looking something like this:

<select id="splitUserDDL" name="splitUserDDL[]"></select>

When I attempt to add options, it seems that the first select box is being populated but not the rest. Is there a way that I can add the same options to all of the select boxes?

    $('#splitUserDDL').empty();
    var userDDL = document.getElementById('splitUserDDL');
    var defaultoption = document.createElement('option');
    defaultoption.text = '-Select-';
    defaultoption.value = 0;
    userDDL.add(defaultoption);
4
  • Do they all have the same id? If they do, that's invalid HTML and your exact problem. Also, why are you creating a 'label' option, rather than using an <optgroup> with a label attribute? Commented Jul 5, 2014 at 18:06
  • 2
    Elements need to have unique IDs. document.getElementById just returns the first match. Commented Jul 5, 2014 at 18:07
  • try $('#splitUserDDL').append(defaultoption); Commented Jul 5, 2014 at 18:07
  • instead of id="splitUserDDL" use class="splitUserDDL" Commented Jul 5, 2014 at 18:11

1 Answer 1

1

Use a class instead of ID.

<select class="splitUserDDL" name="splitUserDDL[]"></select>

Then use jQuery to add the option, and loop over all of them:

$(".splitUserDDL").empty();
$(".splitUserDDL").each(function() {
    $(this).append($("<option>", {
        text: "-Select-",
        value: 0
    });
});
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.