Riyan
Riyan

Reputation: 187

Ajax/JQuery id referencing over multiple table rows

Having problems with assigning a specific id to a varied list of items selected from a table so that the user can click on that item thus executing some Ajax/Jquery, etc.

/** this code had been cut, '$row' is required **/
while($row = mysql_fetch_array($sql)){  
    echo "<tr><td>
          <a id='event_add' title='Add Event' href='javascript:void(0)'>
          <img border='0' src='add_button.gif' width='25' height='25'/></a>
    </td></tr>";
}

Is it possible to have it like this and refer to the id easily using the following?

    $('#event_add').click(function(){
    var row = ($(this).parent().parent().children().index($(this).parent()))-1;
    $.ajax({
        type: "GET",
        url: "add_event.php",
        data: "row="+row+"&do=addEvent",
        cache: false,
        async: false,
        success: function(result){
            alert(result);
        },
        error: function(result){
            alert(result);
        }
    });         
});

Any advice on this problem would be greatly appreciated! :)

Upvotes: 0

Views: 929

Answers (2)

Rob Williams
Rob Williams

Reputation: 1470

You could print a row identifier into your output code.

/** this code had been cut, '$row' is required **/
while($row = mysql_fetch_array($sql)){  
    echo "<tr><td>
          <a class='event_add' data-rowid='" . $row['id'] . "' title='Add Event' href='javascript:void(0)'>
          <img border='0' src='add_button.gif' width='25' height='25'/></a>
    </td></tr>";
}

and then, in your function, row would be defined as

var row = $(this).attr('data-rowid');

Also, change your function assignment code to use a class selector as well.

$(".event_add").click(...)

Upvotes: 1

Gowri
Gowri

Reputation: 16835

why don't you use

Class instant of id

change

html

id='event_add' to class='event_add'

script

$('#event_add') to $('.event_add')

Upvotes: 2

Related Questions