Elaine’s jQuery Lessons: Part 2

For the BEIM NZ Fire project there’s a rather large form that needed styling, this form has sections where you can click a button and add a new row of input elements, each row has a link for them to delete the row if they make a mistake.

Originally the code was structured as a list item, clicking on ‘add new’ would simply add a new list item and clicking on delete would just delete the entire list item.

Here’s the original code for the Delete link

<a href="javascript:void()" onclick="$(this).parent().remove();">Delete</a>

So what this is saying is, when you click on this element, go to its parent and remove it. So in this case the link was sitting inside the <li> so it removed the list item and whatever was sitting inside of it.

I needed to refactor the code from a list item into a table so clicking on this link no longer worked. The input element and the delete link were in separate table cells so clicking on this link would remove the cell the link was sitting inside of.

I needed it to traverse up the tree and remove the whole table row so I did some research, then came across .closest() and its description was: Get the first element that matches the selector, beginning at the current element and progressing up through the DOM tree. Perfect, just what I needed.

<a href="javascript:void()" onclick="$(this).closest('tr').remove();">Delete</a>

So after a bit of tweaking, here is the code I came up with. Here’s an explanation: When you click on this item, find the closest table row (beginning at the current element and progressing up the tree) and remove it.

Again, like my previous post, there was little change on my behalf but it was still frustrating trying to look for something I didn’t know existed, I knew what I wanted it to do, but finding a solution was hard because I’m not aware of most of the jQuery selectors.

This little jQuery snippet wasn’t something I was asked to do, I knew the link no longer worked and I wanted to challenge myself to see if I could fix it on my own, I’m glad I gave it a shot and I’m always finding jQuery opportunities whenever possible.