Spedwards
Spedwards

Reputation: 4492

this + class selector?

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

Answers (3)

David Thomas
David Thomas

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);
});

JS Fiddle demo.

Or, to use specific elements' ids 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();

JS Fiddle demo.

Reference:

Upvotes: 2

Arun P Johny
Arun P Johny

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

adeneo
adeneo

Reputation: 318202

You can use next() to target the next element after the input

$('input[type=text]', '#max, #onepoint, #leftover').on('change', function() {
    $(this).next('.more').toggle( !!this.value.length );
});

FIDDLE

Upvotes: 2

Related Questions