Reputation: 4492
Currently, I have three input fields. When one has text in it, an anchor will show to the right. Currently though, when I type in one, the anchor will appear for all three input fields.
What I need to know is, is there a this + class selector for jQuery? For example:
$(this + '.more')
This is something I need right now and I can't seem to find it or anything similar in the jQuery API.
HTML:
<div id="max">
<span class="sub title">Max</span>
<input type="text" /><a class="more" href="" onclick="">...more</a>
</div><div id="onepoint">
<span class="sub title">One Point</span>
<input type="text" /><a class="more" href="" onclick="">...more</a>
</div><div id="leftover">
<span class="sub title">Leftover</span>
<input type="text" /><a class="more" href="" onclick="">...more</a>
</div>
Javascript:
$('#max input[type=text], #onepoint input[type=text], #leftover input[type=text]').on('change', function() {
if( $(this).val() == '' ) {
$('.more').hide();
} else {
$('.more').show();
}
});
If I have the selector as just $('.more')
all three toggle when I only want the right one too. How would I do this?
Upvotes: 1
Views: 99
Reputation: 253318
I'd personally suggest amending your initial selector to:
$('div[id] > input[type="text"]').on('change', function(){
$(this).next('a').toggle(this.value.length);
});
Or, to use specific elements' id
s as identifiers (but still shorten the selector chain a little):
$('#max, #onepoint, #leftover').find('input[type="text"]').on('change', function(){
$(this).next('a').toggle(this.value.length);
}).change();
Reference:
Upvotes: 2
Reputation: 388316
it is the next sibling of the changed input
element so use .next() and to change the display use .toggle() instead of show/hide
$('#max input[type=text], #onepoint input[type=text], #leftover input[type=text]').on('change', function () {
$(this).next('.more').toggle($(this).val() != '');
});
Upvotes: 1