1
$("#showKey").each(
    $(this).click(function(){
        alert($(this).attr("value"));
    })
);

And

<a id="showKey" href="#" value="{{ customer.key }}">
   <span class="icons icon-key"></span>
   Show key
</a>

The alert gives and undefined output, just 'undefined'. I have a list of customers and a click on #showKey should reveal the key for the clicked customer.

Whats wrong with my code?

1
  • Why do you use each on id selector? do you have multiple elements with the same id? It's an invalid HTML! Commented May 10, 2012 at 20:21

4 Answers 4

6

You cannot have multiple elements with the same ID - use a class instead. Additionally, you don't need the call to .each -- use a class selector instead:

$(".showKey").click(function(){
     alert($(this).data("key"));
);

<a class="showKey" href="#" data-key="{{ customer.key }}">Show key</a>
Sign up to request clarification or add additional context in comments.

Comments

3

you can use data attribute:

<a id="showKey" href="#" data-value="{{ customer.key }}">
   <span class="icons icon-key"></span>
   Show key
</a>


$("#showKey").click(function(){
    alert($(this).data("value"));
})

http://jsfiddle.net/LKArX/

Comments

1

You do not need the jQuery each function.

$("#showKey").click(function(){
   alert($(this).attr("value"));
});

Comments

0

The problem with your code is in your usage of

$("#showkey").each({...});

You should simply use

$("#showkey").click({function(){
   alert( $this).val() );
   }
});

to bind the click event to every showkey id'd element.

Comments

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.