0

I have been trying to use jquery click event with an element in php for loop. How can I transfer the counter value to jquery before click.

My PHP Code:

<?php $counter=0;foreach($a as $abc){$counter++;?>
        <div id="mail_<?php echo $counter;?>" class="ma" />
   <?php }?>

Jquery Code:

$(document).ready(function(){
  $(".ma").click

How could I use this counter variable before click in jquery.

3
  • Before Click means? Onload itself? Commented Apr 26, 2013 at 7:07
  • How could I get that counter variable value anyhow?? Commented Apr 26, 2013 at 7:08
  • parseInt(element.getAttribute('id')) ? Why do you even need this anyway ? Commented Apr 26, 2013 at 7:10

2 Answers 2

1

Why "before" click ? In the following example, you get the counter value of the clicked element.

$(".ma").on('click', function(e) {
  var counter = $(this).attr('id').split('_')[1];
});

Note that you can do the same thing without using id as your counter starts at 0 and just increment one by one.

  $(".ma").on('click', function(e) {
     var counter = $(this).index();
    });

If you need the final value of counter, you can use $(".ma").length

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

2 Comments

how could jquery will identify which element was clicked??
$(".ma") means all element with class "ma". Inside the click event handler of this selector, $(this) refers to the currently clicked ".ma" element. api.jquery.com/click
0

Example : Full HTML Code. Just copy, Paste & Run in Browser. [Used @RafH's Solution]

<html>
    <head>
       <title>jQuery Test</title>
    <style type="text/css">
    div { color:blue; margin:3px; cursor:pointer; }
    </style>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.js"></script>
     <script type="text/javascript">

    $(document).ready(function() {
     $(".ma").click(function() {
      var counter = $(this).attr('id').split('_')[1];
      alert("Counter ID "+counter);
    });
    }); 

    </script>
    </head>
    <body>
        <?php 
        for($counter=1;$counter<=10;$counter++)
        {
        ?>
        <div id="mail_<?php echo $counter;?>" class="ma" />Test</div>
       <?php 
       }
       ?>

    </body>
</html>

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.