Prinz Nikko
Prinz Nikko

Reputation: 1

Javascript function only works once. Any idea why?

HTML

I am trying to create a todolist application. I wanted to make each task list to be removed with faded transition. I achieved it already but the problem with my code is that it only hide the first div area.

<div id="task">
            <input type="checkbox" id="completed">
            <h2>Buy some fruits</h2>
        </div>
        <div id="task">
            <input type="checkbox" id="completed">
            <h2>Buy some fruits</h2>
        </div>

JQuery

 $("#completed").change(function(){$("#item").fadeToggle("fast", "linear")});

Upvotes: 0

Views: 258

Answers (4)

YogaV
YogaV

Reputation: 21

id of both input elements are same.

you can use class instead of id.

like below

$(".completed").change(function(){ } $(this).hide();});

pls modify this code as per u r

Upvotes: 0

Vicky Gonsalves
Vicky Gonsalves

Reputation: 11707

Try this:

<div>
    <input type="checkbox" class="checkbox">
    <h2>Buy some fruits</h2>
</div>
<div>
    <input type="checkbox" class="checkbox">
    <h2>Buy some fruits</h2>
</div>
<script type="text/javascript">
    $(".checkbox").change(function(){$(this).parent().fadeToggle("fast", "linear")});
</script>

OR

<div>
    <input type="checkbox">
    <h2>Buy some fruits</h2>
</div>
<div>
    <input type="checkbox">
    <h2>Buy some fruits</h2>
</div>
<script type="text/javascript">
    $("input[type=checkbox]").change(function(){$(this).parent().fadeToggle("fast", "linear")});
</script>

Upvotes: 0

Vivek Pradhan
Vivek Pradhan

Reputation: 4847

You should not have multiple elements with the same id. The whole point of this attribute is to uniquely identify an element.

Replace it with something like:

  <input type="checkbox" class="completed">

And your javascript accordingly:

  $(".completed").change(function(){$("#item").fadeToggle("fast", "linear")});

This should sort your problem out.

Upvotes: 0

Ankit Tyagi
Ankit Tyagi

Reputation: 2375

Dont use mutipple id's on same page use class instead

<div class="task">
   <input type="checkbox" class="completed">
   <h2>Buy some fruits</h2>
</div>
<div class="task">
   <input type="checkbox" class="completed">
   <h2>Buy some fruits</h2>
</div>

 $(".completed").change(function(){$("#item").fadeToggle("fast", "linear")});

// same apply to your #item 

Upvotes: 5

Related Questions