hotbot86
hotbot86

Reputation: 243

jQuery: selecting the first instance of an element that occurs after another specified element

Using this as a simplified example, assume I have a table that has some radio buttons in it followed by a div element with a link in it. This pattern is then repeated some unknown number of times like so:

<table class="rdoBtnList">
    <tbody>
       <tr>
          <td> Person 1 </td>
          <td>
            <label for="rb1">Verified</label>
            <input type="radio" id="rb1" name="rdoBtns" value="Verified" />
            <label for="rb2">Not Verified</label>
            <input type="radio" id="rb2" name="rdoBtns" value="NotVerified" />
          </td>
       </tr>
    </tbody>
 </table>
 <div class="PersonLink"><a href="#">Link to Person 1 page</a></div>
  ..... tables and divs for person 2, 3, ... n, etc

I would like to be able to use jQuery to enable/disable the link in the div following the radio buttons based on the value of the radio button. I can get the value of the radio buttons, but cannot figure out what selector syntax I would use to enable/disable just the div after the radio buttons.

Here is my jQuery so far:

    <script type="text/javascript">
       $(document).ready(function() {
           $(".rdoBtnList > tbody > tr > td > input").change(function() {
           if ($(this).val() == "Verified") {
               // select the link in the div following the table and enable it
           } else {
               // select the link in the div following the table and disable it
           }
        });
       });
    </script>

Upvotes: 1

Views: 3028

Answers (2)

Kalle
Kalle

Reputation: 2293

I would have tried a different approach, giving each link an id, or perhaps even a class for easier selection:

<table>...
    <input type="radio" id="personXrb1" class="personXselector" ...
<div>
<a href="personXlink" id="personXselector">link to person X</a>

This should be relatively easy as I expect the html is generated programatically. Right? It will also be less prone to errors due to code changes, and possibly easier to read.

Selection would then not be done with $(this).closest etc, which is not guaranteed to work after changing the code around, but instead through

$('#' + $(this).attr('class')).doStuff();

I'm also not sure that enable/disable will work with a div or a-tag, you might be better off using fadeOut() and fadeIn() or just show() and hide() to "disable" the links.

Upvotes: 0

SLaks
SLaks

Reputation: 887453

Like this:

$(this).closest('.rdoBtnList').nextAll('.PersonLink:first').children('a').whatever

closest('.rdoBtnList') will find the table, and nextAll('.PersonLink:first') will find the first .PersonLink after the table.

By the way, the val function returns a normal boolean. You should write if($(this).val()).

Upvotes: 4

Related Questions