Skip to content Skip to sidebar Skip to footer

Jquery, Script Doesn't Recognize Newly Appended Elements

I have a short script that styles form radio buttons. Check working example http://jsfiddle.net/YJRsk/. This works great when radio buttons already exist in DOM. So when page load

Solution 1:

Use a CSS rule and add a class to all radio buttons. If you are using advanced jQuery selectors for styling, I'd recommend simply applying that styling function on creation of each new element.

Edit: The basic problem here is that your .js files are loaded on page load, so if you use something like:

$(".mybutton").click(function() {
    alert("test");
});

This event will only be 'tacked onto' .mybutton elements that exist at page load. If you create/add elements dynamically, you will have to assign the above event handler to them again.

This also has the effect that your uniqid() function will be creating the same id for all radio buttons added currently. Do it like this instead:

$('button').live('click', function() {
    var item = '<li><input type="radio" value="'+uniqid()+'" class="styled" name="test"/><label class="radioButton">Radio button</label></li>';
    $(item).appendTo('#radio');
})

Edit 2:

I don't know what jQuery styling you are using for your radio button, but the basic idea is to use the styling function on your newly created button each time. See this fiddle: http://jsfiddle.net/YJRsk/11/

If I am still missing something, please elaborate and show us the jQuery you use for radio button styling.

Solution 2:

If you know the maximum number of radio buttons, this is what I would do:

  1. Add maximum number of radio buttons to the form (show just those which you wan't to be shown at the beginning)

  2. Leave a script to style them

  3. On button click, just show already styled radio buttons one by one

I hope I was clear enough.

Solution 3:

You forgot to add a piece of your HTML code in the Javascript.

var item = '<li><spanclass="radio"style="background-position: 0pt 0pt;"></span><inputtype="radio"value="'+uniqid()+'"class="styled"name="test"/><labelclass="radioButton">Radio button</label></li>';

$('button').live('click', function() {
    $(item).appendTo('#radio');
})

http://jsfiddle.net/YJRsk/3/

That said, it's probably a smarter idea to style your radio buttons using CSS

Post a Comment for "Jquery, Script Doesn't Recognize Newly Appended Elements"