A_funs
A_funs

Reputation: 1246

jquery .attr variable use

I am trying to get the following simple function to open divs with the same name of the grabbed "name" attributes in other divs, any help would be appreciated.

<script type="text/javascript">
 $(document).ready(function(){
 $('.div').click(function(){
     var nip = (this).attr("name");
     $('#nip').show()
 })
    });

 </script>  

Upvotes: 0

Views: 1151

Answers (3)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039438

Use $(this).attr("name") instead of (this).attr("name") to get the name. Then, use $('#' + nip) to select the desired element.

Your current selector does not work, because the variable name is contained within quotes, causing "nip" to be literally interpreted as "nip".

$(function() {
    $('.div').click(function() {
        var nip = $(this).attr('name');
        $('#' + nip).show();
    });
});

Upvotes: 3

Nix
Nix

Reputation: 6018

Not 100% what you're trying to do, but try this:

$("div").click(function(){
 var nip = "#" + $(this).attr("name");
 $(nip).show();
});

Also, you should clean up your code a little. Are you actually calling out a class called "div"? Remember to close things properly.

Upvotes: 0

Patrick Desjardins
Patrick Desjardins

Reputation: 140993

<script type="text/javascript">
 $(document).ready(function(){
 $('.div').click(function(){
     var nip = ($this).attr("name");
     $('#' + nip).show();
 })
    });

 </script>

You can also use

<script type="text/javascript">
 $(document).ready(function(){
 $('.div').click(function(){
     var $nip = ($this).attr("name");
     $nip.show();
 })
    });
  </script>

Upvotes: 0

Related Questions