views:

1309

answers:

4

I have a form select element that, when a certain value is selected, will toggle two other elements on the page (a dt / dd pair).

The event is triggered correctly, but I can't get the elements to toggle - note I am using class selectors because the number of these element "sets" on the page is variable. Here is my code:

$(".lender_id").change(function () {
if($(this).val()=='45')
   {
   $(this).next(".lender_other1").toggle();
   $(this).next(".lender_other2").toggle();
   }
});

lender_id is my select element class, html code as follows (as stated this element set can appear multiple times on the page):

<dt>Lender</dt>
<dd><select name="lender_id[1]" class="lender_id">
<option value="1">Value</option>
<option value="45">Special Value</option>
</select></dd>

<dt class="lender_other1" style="display:none;">Lender Name</dt>
<dd class="lender_other2" style="display:none;">
<input type="text" name="lender_other[1]" value="" /></dd>

<dt>Lender</dt>
<dd><select name="lender_id[2]" class="lender_id">
<option value="1">Value</option>
<option value="45">Special Value</option>
</select></dd>

<dt class="lender_other1" style="display:none;">Lender Name</dt>
<dd class="lender_other2" style="display:none;">
<input type="text" name="lender_other[2]" value="" /></dd>

etc...
+2  A: 

next() doesn't do what you think it does. Try $(this).parent('dl').find('.lender_other1'). Or, y'know, maybe just $('.lender_other1').

chaos
I tried $(this).parent('dl').find('.lender_other1').toggle(); but it doesn't seem to work. Just $('.lender_other1') would toggle all elements of that class, when I need to only toggle the various next instance of that class. I've updated my question to provide better context.
BrynJ
+1  A: 

.next() only returns the next match, so I think you should be using .nextAll()

http://docs.jquery.com/Traversing/nextAll#expr

ScottE
Would that be in the format $(this).nextAll(".lender_other1").toggle();? If so, that doesn't appear to work either. Any ideas why? Thanks.
BrynJ
Because the select isn't at the same hierarchical level as the elements you're trying to target.
chaos
good point - didn't see the <dd>. Don't see those tags very often. Anyway, you'll have to go up to the parent first, then use nextAll()
ScottE
Just looking again, nextAll() won't work either as the other classes are at the same depth in the hierachy. I'll take a look at this again...
ScottE
A: 

use slice(start, end) method . this is the correct way according to a video of john resig.

Elzo Valugi
+1  A: 

here is what you want:

$(".lender_id").change(function() {
    if ($(this).val() == '45') {
        $(this).parent().nextAll(".lender_other1:first, .lender_other2:first").toggle();
    };
});

EDIT

I combined the class selectors together to make it more efficient.

ScottE
Superb - works great. Thanks!
BrynJ