Question

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...
Was it helpful?

Solution

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.

OTHER TIPS

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

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

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

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

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