Genadinik
Genadinik

Reputation: 18649

How come <a> tag does not produce a clickable link?

I have a link that looks like this:

<p class="half_text"><?php echo $upvotes; ?> <strong>
<a id="vote_up" style="color: #295B7B; font-weight:bold;" href="">Vote Up</a>
</strong> | <?php echo $downvotes; ?> <strong>
<a id="vote_down" style="color: #295B7B; font-weight:bold;" href="">Vote Down</a>    
</strong></p>

and some jQuery code that I am trying to get called.

<script type="text/javascript">
$('#vote_up').click(function() 
{
    alert("up");
});
</script>

But for some reason the alert does not fire when the vote up or down links are pressed. Any idea what I am doing wrong?

You can see this for yourself here: http://www.problemio.com

Upvotes: 1

Views: 121

Answers (5)

ipr101
ipr101

Reputation: 24236

Not sure if this is causing your problem but you have duplicate ids on your page.

Try changing 'vote_up' and 'vote_down' to classes.

Upvotes: 2

martincarlin87
martincarlin87

Reputation: 11062

Not sure if it's necessary but try putting a # in the href attribute.

Also, you are using id attributes for your links when there are more than one of each on the page, you should use class instead.

Upvotes: 3

recursive
recursive

Reputation: 86154

The id attribute is supposed to be unique across a document. If you want it to apply to multiple elements, consider using a class instead.

Upvotes: 2

Rob W
Rob W

Reputation: 349232

Wrap your code in a .ready() handler. The shortcut is $(function(){...}):

$(function(){
   $('#vote_up').click(function() {
      alert("up");
   });
})

is equivalent to $(document).ready(function(){....}).

Upvotes: 4

James Hill
James Hill

Reputation: 61872

You need to place your code inside the .ready() handler:

$(document).ready(function() {
    $('#vote_up').click(function() 
    {
        alert("up");

        //Return false to prevent page navigation
        return false;
    });
});

Take a look at the .ready() docs: http://api.jquery.com/ready/

Here's a working jsFiddle.

Upvotes: 7

Related Questions