0

How do you make this work? <select id="sel[]">, which is an array of all the dropdown boxes.But if I change $('#sel').change(function() { to $('#sel[]').change(function() {, it does not work?

2 Answers 2

1

You can escape the square brackets by two back slashes \\.

$(function() {
    $('#sel\\[\\]').change(function() { ... });
});

Demo

But ideally you should not use such conventions for naming ids.

Sign up to request clarification or add additional context in comments.

1 Comment

\\ will escape the special characters used in jQuery selector as per jQuery docs.
1

The string sel[] is not a valid element id:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").

Reference

Better to use a simpler id like selArr, for example.


An array of drop-down options will not automatically be created for you. You'll have to maintain the data model yourself, like:

var opts = ['one', 'two', 'three'];

Then add to this array as necessary, and build your drop-down out of it:

This approach keeps the model and view separated, a good programming practice for user interfaces.

1 Comment

@Will see update. The id attribute is simply a unique identifier, you'll have to create and maintain an array separately.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.