Search code examples
javascriptjqueryjquery-selectorsjquery-ui-multiselect

jquery reference ID with space in name


I am using jquery with a jquery multi select extension.

For my html syntax:

<select multiple="multiple"  id="test">
<option value=1>1</option>
<option value=2>2</option>
<option value=3>3</option>
</select>

I then get the values of the multi-select with:

  $(function() {

        $('#test').change(function() {
            console.log($(this).val());
        }).multipleSelect({
            width: '100%'
        });
    });

This works 100%.

my question is how do I get this to work when the ID has a space in it. I know it isnt ideal to have a space in an ID or Name but it is what it is currently and I need to get the multiple select options from the ID with a space. so example:

<select multiple="multiple"  id="test two">
    <option value=1>1</option>
    <option value=2>2</option>
    <option value=3>3</option>
    </select>

$(function() {

            $('#test two').change(function() {
                console.log($(this).val());
            }).multipleSelect({
                width: '100%'
            });
        });

this fails with the space in it.

I have tried a few options like below without any success.

any advice appreciated a always.

$(function() {

$("#test two").change(function() {
                    console.log($(this).val());
                }).multipleSelect({
                    width: '100%'
                });
            });

Solution

  • The jQuery documentation has a comprehensive page on Selectors. You'll find all of the selectors that you can use to query based on attributes (which the id is), but it also has this piece of advice:

    To use any of the meta-characters ( such as !"#$%&'()*+,./:;<=>?@[\]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\. For example, an element with id="foo.bar", can use the selector $("#foo\\.bar").

    So you have two options:

    $('#test\\ two')
    

    or

    $('[id="test two"]')
    

    All of that said, the HTML spec doesn't allow spaces in the id attribute on elements. The browser will probably still render the page as you'd expect, but you really shouldn't do it if you can avoid it; if only because it makes things much more complicated than they need to be, as you've found out.

    The value must be unique amongst all the IDs in the element's home subtree and must contain at least one character. The value must not contain any space characters.