jquery ui multiple dynamic dialogs
-
18-09-2019 - |
Question
So I have like a list of users on a page. each user name is clickable and it displays the user information in the dialog. Right now I'm using a static length for the list. I would like jquery to see how big the list of users is and apply the code to the list.
Check out the code here:
$(function() {
var options = {
autoOpen: false,
width: 'auto',
modal: true
};
$([1, 2, 3, 4]).each(function() {
var num = this;
var dlg = $('#dialog-player-' + num).dialog(options);
$('#player-link-' + num).click(function() {
dlg.dialog("open");
return false;
});
});
});
I looked at this page of the documentation: each What I tried is to select all divs in container "div#parent". Like so:
$(function() {
var options = {
autoOpen: false,
width: 'auto',
modal: true
};
$("div#parent div").each(function() {
var num = this;
var dlg = $('#dialog-player-' + num).dialog(options);
$('#player-link-' + num).click(function() {
dlg.dialog("open");
return false;
});
});
});
But that didn't work. Anybody know of any other way to do this ?
Solution
I've noticed a bug in your code and fixed it for you:
$(function() {
var options = {
autoOpen: false,
width: 'auto',
modal: true
};
var num = 1;
$("div#parent div").each(function() {
var dlg = $('#dialog-player-' + num).dialog(options);
$('#player-link-' + num).click(function() {
dlg.dialog("open");
return false;
});
num = num + 1;
});
});
OTHER TIPS
$(function() {
var options = {
autoOpen: false,
width: 'auto',
modal: true
};
$(['George', 'Ralph', 'Carmine', 'Suzy']).each(function(index, val) {
var num = index;
var dlg = $('#dialog-player-' + num).dialog(options);
$('#player-link-' + num).click(function() {
dlg.dialog("open");
return false;
});
});
});
You had the right idea the first time. Just use the index supplied by the each function. No need for a separate counter.
look up 'children' in the docs - I think you might need to cycle through the children of the element using each rather than what you have done. e.g.
$("div#parent").children('div').each(function(){etc...})