user1283226
user1283226

Reputation: 17

jquery issue checkbox that hides the input next to it

i have a lot of checkboxes and for each one i have an input field next to it i want when i click on each checkbox .. the input next disapear ! so i did this .. and it looks logical to me but it's a mess

$(":checkbox").click(function() {
    $(":checkbox").next().hide();
});

but it hides all the inputs of the documents so i tryed this

this.next().hide();

but it's not working ! i tried this in staid !

for(i=0;i<$(":checkbox").length;i++){
  $(":checkbox").eq(i).click(function() {
      $(":checkbox").eq(i).next().hide();
   });
}

and still not working ! what's wrong with my logic ?

Upvotes: 0

Views: 39

Answers (3)

Lix
Lix

Reputation: 47966

What you want to use as a selector for your checkboxes is this -

$('input:checkbox');

Secondly, within the callback of the click handler, you can use the $(this) keyword to access the specific element that created the event.

$("input:checkbox").on('click',function() {
  $(this).next().hide();
});

I like to be very verbose with my selectors to improve readability, so as a final suggestion, why not give a selector to the next() function and specify that you want to look for the next input element?

  $(this).next('input').hide();

Upvotes: 1

Stuart Burrows
Stuart Burrows

Reputation: 10814

It should be:

$(":checkbox").click(function() {
    $(this).next().hide();
});

this and $(this) are quite different, I'd recommend reading through the jQuery documentation for more information as it is pretty fundemental...

Upvotes: 1

elclanrs
elclanrs

Reputation: 94101

Try:

$('input[type=checkbox]').change(function() {
  $(this).next().toggle();
});

Upvotes: 3

Related Questions