Question

I'm sure this is a simple problem. I have several rows in a table like this:

   <tr>
    <td>
      <select class="UsersSelect">
        <option value="user-whatever">User Whatever</option>
      </select>
    </td>
    <td>
      <a class="EditButton"><span class="ui-icon ui-icon-pencil"></span></a>
    </td>
   </tr>

Here is the jQuery:

$('.EditButton').click(function() {
   $('<option>test</option>').appendTo($(this).closest('select.UsersSelect'));
...
});

This results nothing at all. I believe my error is in using $(this) improperly but can't figure out how I screwed it up.

Hopefully my goal is obvious enough. Just to clarify, I'm trying to append to the closest select ONLY, it will never be more than one at a time and always in the directly above.

Thanks so much for your time!

Was it helpful?

Solution

Since the select isn't a sibling or parent, you have to do some more logic with your selector:

var container = $(this).closest("td").prev("td").find("select.UsersSelect");
$('<option>test</option>').appendTo(container);

OTHER TIPS

select.UsersSelect is not a parent of .EditButton. That's why nothing is happening.

Use this instead:

$('.EditButton').click(function() {
   $(this)
     .closest("tr")
     .find("select.UsersSelect")
     .append('<option>test</option>');
   // ...
   return false;
});

JSFIDDLE

Try:

$('.EditButton').click(function() {
   $('<option>test</option>').appendTo($(this).closest('td').prev().find('select.UsersSelect'));
});

jsFiddle example

.closest() travels up the DOM and in your example it would go to the parent td, then the parent tr, the the table, missing the select altogether.

change this:

$('<option>test</option>').appendTo($(this).closest('select.UsersSelect'));

to this:

$('<option>test</option>').appendTo($(this).closest('tr').find('select.UsersSelect'));

you need to traverse up to the tr with .closest() and then you can use .find() method to get the target.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top