0

I have a simple script that shows an element based on which option you choose.

Example:

<select id="my-selector">
   <option value="cat">Cat</option>
   <option value="dog">Dog</option>
</select>

<div id="cat" class="hideme" style="display:none">
    Cat
</div>

<div id="dog" class="hideme" style="display:none">
    Dog
</div>

<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<script>
$(function() {
    $('#my-selector').change(function(){
        $('.hideme').hide();
        $('#' + $(this).val()).show();
    });
});
</script>

But I run into problems when periods are introduced, like this:

<select id="my-selector">
   <option value="cat.meow">Cat</option>
   <option value="dog.bark">Dog</option>
</select>

<div id="cat.meow" class="hideme" style="display:none">
    Cat
</div>

<div id="dog.bark" class="hideme" style="display:none">
    Dog
</div>

I know I need to escape the periods, but the problem is that the values of the selection field and the ID's of the divs are dynamically generated and I have no control over how they are output.

Is there a way to modify the javascript to fix this issue?

User_FTW
  • 504
  • 1
  • 16
  • 44

1 Answers1

1

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

or use attribute-value selector like this:

$('[id="' + $(this).val()+'"]').show();

Working Demo

Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125