0

I am having this problem when I have a for loop of links and I want each link to alert through jquery but only the first link is working.. What could be the problem?

        <link rel='stylesheet' href='CSS/nook.css' type='text/css' media='screen, projection' />
        <script type="text/javascript" src="JS/jquery-1.10.2.min.js"></script> 

This is my script

        <script>
        $(document).ready(function() {
            $("#click").click(function(e) 
            {
                e.preventDefault(); 
                alert("hi");
            });
         })
        </script>

And this is my loop

        <?php
         for($i=0;$i<2;$i++){
           echo "<a href = '' id = 'click'>a</a><br>";
         }
         ?>

2 Answers 2

4

ID of an element must be unique, use class to group similar elements

    <?php
     for($i=0;$i<2;$i++){
       echo "<a href = '' class='click'>a</a><br>";
     }
     ?>

then

    <script>
    $(document).ready(function() {
        $(".click").click(function(e) 
        {
            e.preventDefault(); 
            alert("hi");
        });
     })
    </script>

When you use id-selector, it will return only the first element with the given id others will be ignored. So in your case the click handler will be registered to only the first element withe the id click

Sign up to request clarification or add additional context in comments.

7 Comments

is this possible if i submit a form in the jquery?
@Nhiz you can call $('form').submit()
i seem to get the idea but it isn't working for me. I have two input buttons in my form like this for($i=0;$i<2;$i++){ echo "<form class='post_comment'>"; echo "<div><input type='submit' class='commment' name='comment' value='$i'/></div>"; echo "</form>"; } but whenever i click the button, i can't alert its value
@Nhiz can you share the generated html
how will i do that? sorry i don't get it
|
0

IDs are unique, and you should only have 1 per page. So this is wrong:

<a id="unique"></a>
<a id="unique"></a>

Instead, you need to use a class:

<a class="not_unique"></a>
<a class="not_unique"></a>

The way you access a class with jquery is with . instead of #:

$(".click")

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.