Saint Robson
Saint Robson

Reputation: 5525

Dynamic jQuery Based On HTML <li> Tags

I have HTML code like this :

<li><input type="hidden" value="001" class="block-hidden-input" />
    <a href="#" id="manage-1" class="manage-content-link">
        <img src="images/web-block/web-block1.jpg"/>
        <span class="orange-notice">Click to Edit Content</span>    
    </a>
</li>

<li><input type="hidden" value="002" class="block-hidden-input" />
    <a href="#" id="manage-2" class="manage-content-link">
        <img src="images/web-block/web-block2.jpg"/>
        <span class="orange-notice">Click to Edit Content</span> 
    </a>
</li>

each li tag has unique id and it has following format : id="manage-X". each user can have multiple li tag, so it's dynamic.

on the other hand, I need this jQuery to handle that li tags :

$('#manage-1').click(function(e) { 
    $(this).next(".manage-content-wrap").find(".manage-content").load("file-001.php");
    e.preventDefault();
});
$('#manage-2').click(function(e) { 
    $(this).next(".manage-content-wrap").find(".manage-content").load("file-002.php");
    e.preventDefault();
});

this jQuery looks so awful. because it's static and if I have 5 li tags, means I have to copy-and-paste 5 times. I don't know how to make it dynamic on jQuery.

plus, "file-001.php" and "file-002.php" are based on li's value. so, it must be in this format file-XXX.php (replace XXX with li's value). I guess this must be related with RegEx. but I have no clue how to do it...

any idea how to make that jQuery dynamic based on li tags? thanks!

Upvotes: 1

Views: 237

Answers (3)

pete
pete

Reputation: 25081

Try changing your selector to be class-based. Then you'll simply need a way to figure out which file to load. The following example assumes that the value of your hidden inputs contains the file number to load:

$('a.manage-content-link').click(function (e) {
    var self = $(this),
        file = self.siblings('input[type="hidden"].block-hidden-input').val();
    self.next(".manage-content-wrap").find(".manage-content").load("file-" + file + ".php");
    e.preventDefault();
});

Upvotes: 3

davepmiller
davepmiller

Reputation: 2708

Try a for loop.

for (var i = 0; i < numberOfFiles; i++)
{ 
    $('#manage-'+i).click(function(e) { 
    $(this).next(".manage-content-wrap").find(".manage-content").load("file-00"+i+".php");
    e.preventDefault();
    });
}

Upvotes: 1

Musa
Musa

Reputation: 97672

Try the following, note that "file-00"+this.id.split('-')[1]+".php" will ony cater for file-001.php to file-009.php but you should be able to work it it out for values grater than 9

$('[id^=manage-').click(function(e) { 
    $(this).next(".manage-content-wrap").find(".manage-content").load("file-00"+this.id.split('-')[1]+".php");
    e.preventDefault();
});

Upvotes: 2

Related Questions