0

So I am working with a couple ascx with different checkbox areas on each control. I originally used

 $('[type=checkbox]').click ( function(){ code });

and it did the job, At first. But when i added another control, also using checkboxes, the function was firing for the other checkboxes as well so i upgraded the js to

 $('#chck').click(function(){ code });

But with this, it only fires an event for the first checkbox in that list.. how can i get it to fire for all clicks?

I have also tried this:

 $('#chck').each(function(){ $(this).click({ function() { code }); });

and this only worked for the first one as well

here is my ascx page example:

 <asp:Repeater ID="contacts" runat="server">
            <ItemTemplate>
                <tr>
                    <td>
                        <input type="checkbox" id="chck" />
                    </td>
                  .....
                 </tr>
             </ItemTemplate>
  </asp:Repeater>

and here is my JS code segment

    $(document).ready(function(){
       $("#chck").each(function () {
           $(this).click(function () { onchange($(this)); });
       });
    });
    function onchange(checkbox) {
    // adds contact to list
    }
1
  • 3
    You should never have multiple of an id. Use a class for that Commented Mar 8, 2013 at 17:50

2 Answers 2

3

ids must be unique. Use a class instead:

<input type="checkbox" class="chck" />
$('.chck').click(function(){ code });
Sign up to request clarification or add additional context in comments.

2 Comments

yep, that'll fix it.. i figured since it was in a repeater n it didn't give a warning or an error, that it was ok.
You can do all kinds of things in .net without compilation errors/warnings that will produce completely invalid html.
1

See using same ids for multiple elems on a same page is invalid.

IDs should be unique to each element. When this happens browser only selects first of it.

To overcome this issue one must change id to class. So you have to do same thing with your markup change id to class:

<input type="checkbox" class="chck" /> // <----change id to class for every input

and now your script should be:

$('.chck').each(function(){ //<-----use '.' notation for class selectors 
     $(this).click(function() { 
         onchange($(this));
     }); 
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.