tags:

views:

202

answers:

1

I have a drop down box next to html link tag element, the link element is as below:

<a href="#" class="delete" onclick="remove(this)"> Delete</a>

It has an onclick attribute set to the javascript function below:

 `function remove(obj) {

    $(obj).prev('select[name=estateDropDownList]').remove();
    $(obj).remove();
}`

Now it removes the link fine, but it won't remove the PREVIOUS dropdownbox, this dropdown box has a name "estateDropDownList" and I just want it to remove only THAT dropdown box using prev() in JQuery, any ideas as to why it only removes the link and not the dropdown box?

+2  A: 

I would change a couple of things first:

<select name="estateDropDownList" class="estate">
  ...
</select>
<a href="#" class="delete">Delete</a>

and then:

$(function() {
  $("a.delete").click(function() {
    $(this).prevAll("select.estate:first").remove();
    $(this).remove();
    return false;
  });
});

The point being that:

  1. Don't use the onclick attribute. Unobtrusive Javascript is all about not littering your markup with Javascript;
  2. Try not to use attribute selectors. They're not quick. Give the relevant elements a class;
  3. this is already set to the anchor that was clicked on. There is no need to pass it in; and
  4. prev() only matches the exact previous sibling. If there is something between the anchor and select then it won't work, which is why I changed it to prevAll() and added :first to get the first one. I'm not 100% sure of the ordering of this. You may need :last instead.
cletus