Reputation: 21998
I have a form with repeating sets of elements.
When a select with class credit_req_select
changes I want to show/hide and possibly clear only the next text input with class credit_line_text
.
The change() func below is not finding the textfields and I think it must have to do with how I am using $(this)
.
What is the correct way to grab these textfields?
My HTML is
<p class="file_info">*Credit Required:
<select name='default_credit_requirements' id='default_credit_requirements' class="credit_req_select">
<option></option>
<option value='1' selected>Do not include</option>
<option value='2' >Include if able</option>
<option value='3' >Must include</option>
</select>
</p>
<p class="file_info">
<label>*Credit Line:
<input type="text" name="default_credit_line" id="default_credit_line" class="credit_line_text" value="" />
</label>
</p>
My function looks like this, same as the answer here Jquery next adjacent selector with $(this)
$('.credit_req_select').change(function() {
if(this.value > 1) {
$(this).next(".credit_line_text").show();
console.log($(this).next(".credit_line_text").attr('id'));
} else {
$(this).next(".credit_line_text").val('');
$(this).next(".credit_line_text").hide();
}
});
I have also tried this answer jquery next() returning nothing
$('.credit_req_select').change(function() {
if(this.value > 1) {
$(this).nextUntil(".credit_line_text").show();
console.log($(this).nextUntil(".credit_line_text").attr('id'));
} else {
$(this).nextUntil(".credit_line_text").val('');
$(this).nextUntil(".credit_line_text").hide();
}
});
Also tried assigning this to a var per jQuery $(this).next() not working as expected
Upvotes: 0
Views: 237
Reputation: 14573
What you should really do is wrap each repeating set of elements
in something. For example a div
with the class element
. Then your select query will be much easier to read.
$(this).closest('.element').find(".credit_line_text")
Upvotes: 0
Reputation: 44740
Try this -
$(this).closest('p.file_info').next().find(".credit_line_text")
As your input is already having an id default_credit_line
and as Id's are supposed to be unique, you can use this.
$('#default_credit_line').val("");
Upvotes: 2