views:

59

answers:

2
<?php foreach ($list as $item): ?>
  <tr>
    <td>
    <div id="<?php echo $item['id']; ?>">
    <input type="text" name="name" id="name"/>
    <button type="submit" id="ajax_submit" value="<?php echo $item['id']; ?>">run</button>
    </div>
    </td>
  </tr>
<?php endforeach; ?>

In this php-code I generate html table. When user click on button they activate this JQuery script

 <script>
   $(document).ready(function(){
     $('button').click(function(){
       var id = "#" + $("button").val();
          $.post("data/js", { name: $("#name").val(),id : id },
           function(data){
            $(id).html(data);
         });
       })
    });
 </script>

But, when I want select non-first button in table, script run function for first. Please help to do all normal.

PS sorry for my english ;-(

A: 

You can use the jQuery $() function to select by ID rather than by element:

 <script>
   $(document).ready(function(){
     $('#ajax_submit').click(function(){
       var id = "#" + $("#ajax_submit").val();
          $.post("data/js", { name: $("#name").val(),id : id },
           function(data){
            $(id).html(data);
         });
       })
    });
 </script>

Note: The id has to be unique. If you want to select another button then give it a different id (e.g. id="second_button) and select it with $('#second_button').

halfdan
+1  A: 

Try this:

<?php foreach ($list as $item): ?>
  <tr>
    <td>
    <div id="<?php echo $item['id']; ?>">
    <input type="text" name="name" id="name"/>
    <button type="submit" id="ajax_submit_<?php echo $item['id']; ?>" value="<?php echo $item['id']; ?>">run</button>
    </div>
    </td>
  </tr>
<?php endforeach; ?>

..

<script>
   $(document).ready(function(){
     $('button').click(function(){
       var id = $(this).attr('value');
          $.post("data/js", { name: $(this).prev().attr('name'),id : id },
           function(data){
            $(id).html(data);
         });
       })
    });
 </script>
Stewie
GREAT THANKS!!!! whole working, i trying to solve this whole day =) thanks thanks thanks ))
NiLL
If this solved your problem, please accept it (click the ✓ beside the answer).
David Thomas
You are welcome :) Also, I noticed that you have $('#name'). I am guessing you will face a problem with this in future too..so, saving you another qustion ..Please change it to this: $(this).prev().attr('name') .. (I fixed it in my code block, above)
Stewie