0

I have a table containing a row for each element in an array. I am trying to remove the element when the delete image is clicked (the image's id is deleteRowButton). At the moment nothing happens when you click the image, however if I remove the var index line, the table row will fade out as expected (but of course the array element is not removed.

$(document).on('click', '#deleteRowButton', function() {
    var index = $(this).closest('tr').attr(id); 
   //Set index to the id of table row (number corresponding to their position in the array)
    remove_index(index); 
    $(this).closest("tr").fadeOut('slow');
    return false;
});

function remove_index(value) {
    $.post("./remove_array_item.php", {index:value});
}       

Here is my code in remove_array_item.php to remove the array element:

<?php  
include("./config/init.php"); //Contains session_start() etc. 

$index = $_POST['index']; //index variable passed in
$ca = $_SESSION["objColl"]; //get array from session variable
$ca->delLineItem($index); //delete item of array at index
$_SESSION["objColl"] = $ca; //store array as session variable 
?>

So what I am wondering is:

  1. Why does the jquery function stop firing if I include:

var index = $(this).closest('tr').attr(id);

i.e. if I comment it out, the function will make the table row fade out.

  1. What is wrong with my function in remove_array_item.php because even when I remove the var index and just pass a value for the index like so

remove_index(1);

It still does not remove the item from the array and so when I refresh the page, the item is back in the table.

2 Answers 2

1

Change var index = $(this).closest('tr').attr(id); to var index = $(this).closest('tr').attr('id'); You forgot the quotes around id.

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

Comments

1

I think you made a mistake by binding on click event to an Id, where as you will have multiple rows. You need to share the HTML to clarify this issue.

A wild guess. Change the #deleteRowButton (id) to .deleteRowButton (class).

Also note that attr() function only accept string as parameter.

$(this).closest('tr').attr("id");

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.