Reputation: 1194
I have a form where I want to show an input box when an option is selected.
The problem: I am allowing users to add more form elements dynamically, so the id's count up, and I'm not sure how to target the current form input, and not every single one.
As an example, after a user adds a 2nd form item I have something similar to this:
<div class="option-wrapper">
<div id="condition-1" class="condition">
<select id="option-1" class="option">
<option value="0">Select...</option>
<option value="1">Option One</option>
<option value="2">Option Two</option>
</select>
<select id="operator-1" class="operator">
<option value="0">Select...</option>
<option value="1">greater than</option>
<option value="2">less than</option>
</select>
<div id="input-1" class="form-input" style="display:none;">
<input id="form-input-1" class="form-input"></input>
</div>
</div>
</div>
<div class="option-wrapper">
<div id="condition-2" class="condition">
<select id="option-1" class="option">
<option value="0">Select...</option>
<option value="1">Option One</option>
<option value="2">Option Two</option>
</select>
<select id="operator-2" class="operator">
<option value="0">Select...</option>
<option value="1">greater than</option>
<option value="2">less than</option>
</select>
<div id="input-2" class="form-input" style="display:none;">
<input id="form-input-2" class="form-input"></input>
</div>
</div>
</div>
Trying to target #input-2 to show it, by using form-input. Only want to show it for the current option-wrapper, inside the wrapper the user is currently working in.
Currently trying:
$('.operator').change(function() {
switch (this.value) {
case '0':
break;
case '1':
$(this).parents('.form-input').toggle();
break;
}
});
I know this use of parents is wrong, I've tried a lot of variations and haven't been able to hit the one I wanted. Any help is appreciated, thanks!
Upvotes: 0
Views: 284
Reputation: 133
I guess when you select .form-input you'll end up with at least 2 elements: the div and the input. With one do will show? Could you try this?
$(this).parent().find('.form-input')[0].toggle();
Upvotes: -1
Reputation: 145408
How about this:
$(this).siblings(".form-input").toggle();
It gets the sibling element with class .form-input
.
Upvotes: 1
Reputation: 150253
What about this:?
$('.operator').change(function() {
if (this.value === 1)
$('.form-input:last').toggle();
});
Or If got you wrong, you might want this:
$('.operator').change(function() {
if (this.value === 1)
$(this).parent().find('.form-input').toggle();
});
Upvotes: 2