4

I have this code:

<ul>
    <li><a href="#" class="service-chooser" id="ubuntu-one">Ubuntu One</a></li>
    <li><a href="#" class="service-chooser" id="ftp">FTP account</a></li>
</ul>

<!-- these div are hidden -->
<div id="ubuntu-one-form" class="hide">
    Ubuntu One credential
</div>
<div id="ftp-form" class="hide">
    Ftp Crediental
</div>

when i click on a link i want to show a div based on the id of the link:

<script type="text/javascript">
$(document).ready(function() {

$(".service-chooser").click(function() {
    var service = $(this).attr('id');
    var service-id = '#' + service + 'form';

      $(service-id).show('slow', function() {
            // Animation complete.
        });

    });

});

</script>

But it doesn't work

Shawn Chin
  • 84,080
  • 19
  • 162
  • 191
Matteo Pagliazzi
  • 5,140
  • 12
  • 49
  • 83

3 Answers3

9

Variable names in JavaScript cannot contain a -. When you open your console, you should have received an error, similar to missing ; before statement.

Valid characters for a variable name are alphanumeric characters, underscore and dollar sign.

You can fix your code by replacing the - by a _:

$(".service-chooser").click(function() {
    var service = this.id           ;           // Example ubuntu-one
    var service_id = '#' + service + '-form';   // Example #ubuntu-one-form

      $(service_id).show('slow', function() {
            // Animation complete.
        });
    });
});

I have also replaced $(this).attr('id') by this.id.
See also: When to use Vanilla JavaScript vs. jQuery?

Community
  • 1
  • 1
Rob W
  • 341,306
  • 83
  • 791
  • 678
0

Your service id also needs to concat a '-' as per your html (<div id="ubuntu-one-form" class="hide">), also your service-id should be service_id:

$(".service-chooser").click(function() {
    var service = $(this).attr('id');
    var service_id = '#' + service + '-form';
scrappedcola
  • 10,423
  • 1
  • 32
  • 43
0

Works here: http://jsfiddle.net/Skooljester/T887t/ Don't have a - in your variable name, and you forgot to add the - when adding the id of the a to the variable.

ayyp
  • 6,590
  • 4
  • 33
  • 47