3

See the code's comment:

$.each($('input[type="radio"]'), function(){
    var input = $(this);
    var container = $('<div class="radio"></div>');
    var mark = $('<span />');

    input.wrap(container).after(mark);

    container.click(function(){
        alert('test'); // Not triggered.
    });
});

The html is:

<input type="radio" value="female" name="gender" />

Anyone know why the alert is not triggered when clicked, and yes it is visible in CSS. When I use :

console.log(container);

It does give me the HTML it is containing.

Thanks

3 Answers 3

5
$('body').on('click', 'div.radio', function() {

});

Full Code

$('body').on('click', 'div.radio', function() {
  alert('test'); 
});

$.each($('input[type="radio"]'), function(){
    var input = $(this);
    var container = $('<div class="radio"></div>');
    var mark = $('<span />');

    input.wrap(container).after(mark);
});

NOTE

Instead of body, you should use a static-element that is the container of container.


Why you need this

You need delegate event handler, as your element added to DOM dynamically that means. after page load.

Sign up to request clarification or add additional context in comments.

1 Comment

Why did you add that note about the body? Using the document element is actually recommended as per the jQuery documentation. "Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers."
1

after some tested it seems to me that the "wrap" clone the object you pass it as argument, or reference to the object is lost but I'm not so sure.

a first solution is to assign the event "onclick" before moving the object in the "wrap".

$.each($('input[type="radio"]'), function(){
    var input = $(this);
    var container = $('<div class="radio"></div>');
    var mark = $('<span />');

    $(container).click(function(){
        alert('test'); // triggered now.
    });

    input.wrap(container).after(mark);
});

a simplified version :

$.each($('input[type="radio"]'), function(){

    var wrapper = $('<div class="radio"></div>').click(function(){
        alert('test'); // triggered now.
    });

     $(this).wrap(wrapper).after($('<span />'));
});

dont forget to decalare this function in the onload function

$(function(){

   // your code here ....
});

Comments

0

I was also affected by this and found that on is available only with jquery 1.7 and above. I am on jquery 1.4.1 and on is not available with version. Upgrading jquery was something I wanted to avoid.

Thankfully delegate was there and it solved the problem.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.