0

I have to add a list of checkboxes dynamically. I then need to know which one performed the click, then ask if it's checked or not.

I have this code:

   $('#MyContainerOfChecksDiv').click( '.MySelectorClass', function(){

     if ("MyCheckClicked".is(':checked'))
       {
         //...here i need to use the label and id 
       }
    else{...}
    })

using "$(this)" i get the "MyDiv", obviously using $(this).find('input:checkbox') I get the whole list of checks.

I have to get this checkbox because I need to use its properties.

paisanco
  • 4,098
  • 6
  • 27
  • 33
  • 1
    Your function is passed the click event information as a parameter. You can get the exact element clicked from that. – celticminstrel Jul 03 '15 at 01:59
  • I think you might be mistaking [`.click`](https://api.jquery.com/click/#click-eventData-handler) for [`.on`](https://api.jquery.com/on/#on-events-selector-data-handler) – Stryner Jul 03 '15 at 02:03
  • Can include `html` at Question ? – guest271314 Jul 03 '15 at 02:03
  • Why are you passing `.MySelectorClass` to `.click`? If you're doing event delegation to dynamic elements, you have to use `.on()`. – Barmar Jul 03 '15 at 02:17

2 Answers2

0

Add a formal parameter to click handler and use it like this

$('#myDiv').click('.MySelectorClass', function (e) {
    if ($(e.target).is(':checked')) {
        alert(e.target.id);
    }
})

fiddle
Also it's not quite clear to me how you distinguish dynamically added elements and static. Do you have different class for them? If so then you dynamic and static elements can have different handlers and this will be the way to tell whether it was created dynamically

Kirill Slatin
  • 6,085
  • 3
  • 18
  • 38
  • thanks to everyone i have the solution like this [fiddle solution](http://jsfiddle.net/ys0ktym1/6/) , i was making some mistakes. just two more things - in this case what's the difference between '$(e.target)' and '$(this)' - i don't get the difference betweet '.on('click'...)' and '.click(...)' thanks again – Felipe Sierra Jul 04 '15 at 00:47
  • `.click(handler)` is a shortcut for `on('click', handler)` . Read [jquery docs](https://api.jquery.com/click/) for details. `this` and `e.target` make difference when handler is attached to a parent element http://stackoverflow.com/a/21667010/4573999 – Kirill Slatin Jul 04 '15 at 03:22
0

To delegate to dynamic elements you have to use .on(). The element that you clicked on will be in this.

$("#myDiv").on("click", ".MySelectorClass", function() {
    if (this.clicked) {
        // here you can use this.id
    } else {
        // ...
    }
});

You can't use .click() to delegate like you tried. You're just binding the click handler to the DIV, and the string ".MySelectorClass" is being passed as additional data to the handler.

Barmar
  • 741,623
  • 53
  • 500
  • 612