Thomas
Thomas

Reputation: 1079

jquery remove from dom based on variable

Have a script to add / remove options from a select field -- the "value" of the option I want to remove should be equal to the "class" of the link clicked. I've tried several different versions of this script and I cannot for the life of me figure out how to properly get the variable delText into the function to remove it. help pls!

   $('a.del').click(function() {
      var delText = $(this).attr('class');
      window.parent.$("select[name='<?php echo $f; ?>']").remove($("<option></option>").text(delText));
   });

Upvotes: 0

Views: 1510

Answers (3)

bdukes
bdukes

Reputation: 156055

Select the links via .del means that you aren't going to be able to use their class to also identify their related <option/>. Maybe you could use rel instead (for either value).

$('a[rel=del]').click(function (event) {
    event.preventDefault();
    $('select[name=<?php echo $f; ?>] option')
        .remove('[value=' + $(this).attr('class') + ']');
});

Working example: http://jsfiddle.net/prH9M/

If you pass in a string to remove, it filters the current set (not its children). You could also select the option (via find) and then just call remove, without filtering

$('select[name=<?php echo $f; ?>]')
    .find('option[value=' + $(this).attr('class') + ']')
    .remove();

Upvotes: 0

burkestar
burkestar

Reputation: 777

Try something like:

$("select[name='<?php echo $f; ?>'] > option[value=" + delText + "]").detach();

To select and detach the option with the specified value that is a child (">" selector) of the named select element.

Upvotes: 0

user229044
user229044

Reputation: 239541

If the value of the element is equal to the class of the link, then do this:

$('a.del').click(function() {
  var delText = $(this).attr('class');
  $('option[value=' + delText + ']').remove();
});

I'm not sure if that actually jives with what you're trying to do? The <?php ?> bit seems really out of place, and the I'm not sure about the window.parent bit either.

Upvotes: 3

Related Questions