SpeedCrazy
SpeedCrazy

Reputation: 517

How can I write a function that relies on dynamic selectors?

I am writing a function to dynamically load jQuery UI accordian leaves with content. I know (think) the AJAX part works as I lifted it from another working AJAX loader I have, but the function as a whole does not work.

The code:

    function load_leaf(link){
    var link = link;
    $.ajax({
            cache : false,
            type : 'POST',
            async: false,
            url : 'includes/'+ link +'.php?'+ new Date().getTime(),
            dataType : 'text',
            data: {
                owner : '$user_id'
            },
            success: function(msg){
                $("#" + link).html(msg);
                console.log('Can\'t see me in Chrome, but ok in firefox !')
            },
            error: function() {
                console.log($.makeArray(arguments));
            },
            complete: function() {
                console.log($.makeArray(arguments));
            }

    });
};
$(function(){
    $('.accordian').click(function(){
        var link = this.getAttribute("link");
        load_leaf(link);
    });
});     

For whatever reason this does not work. The break point seems to be this line
$("#" + link).html(msg);
Specifically the selector, as a hard coded selector works perfectly. The link variable is correctly filled i know this as i can alert the value correctly. The link is not the problem as i replaced the whole ajax function with a simple add class and it a still did not work, it also broke at the selector.

EDIT:
This is the div as printed by php:

<h3 class="accordian" id="'.$tab_id.'" link="'.$tab_link.'" >
 <a href="#">'.$tab_name.'</a>
</h3>
<div id="'.$tab_link.'"><p>Hi</p></div>

The html for the first one is:

 <h3 class="accordian" id="accordian_manage.php" link="accordian_manage.php" ><a href="#">Manage Images</a></h3><div id="accordian_manage.php"><p>Hi</p></div>

Upvotes: 2

Views: 100

Answers (2)

Fabr&#237;cio Matt&#233;
Fabr&#237;cio Matt&#233;

Reputation: 70159

Your ID has a period . in it, which jQuery interprets as a chained class selector.

You can either change your link/IDs, or use this hack:

$("[id='" + link + "']");

Live demo

Upvotes: 1

Kabilan S
Kabilan S

Reputation: 1094

I guess your problem is with Jquery is not finding the div to load the msg..Post the accordion div so that i could give you the proper selector

Upvotes: 0

Related Questions