I have multiple divs with the same class name that dynamically populate a container.
<div class="container">
<div class="content cancel"><button class="showModal"></button></div>
<div class="content cancel"><button class="showModal"></button></div>
<div class="content cancel"><button class="showModal"></button></div>
<div class="content cancel"><button class="showModal"></button></div>
<div class="content cancel"><button class="showModal"></button></div>
</div>
Each div.content has a button that will show a jqueryUI dialog. Once the modal is launched, it has two buttons for save and cancel. If cancel is clicked, an alert will show the index position of the div that launched the modal and remove the class “cancel” from the div.content container it was launched from.
<div class="modal">
<button class="save">save</button>
<button class="RemoveCancel">cancel</button>
</div>
Here is my Jquery
$(".modal").on("click", ".RemoveCancel", function () {
var parent = $(this).closest(".content");
var modalTest = $(".content").index(parent);
$("div.content:nth-child(" + (modalTest + 1) + ")").removeClass("cancel");
alert("div.content:nth-child(" + (modalTest + 1) + ")");
});
and for the modal
$(function () {
$(".modal").dialog({
autoOpen: false,
height: 140,
modal: true
});
$(".showModal").live('click', function () {
$(".modal").dialog("open");
return false;
});
$(".save, .RemoveCancel").live('click', function () {
$(".modal").dialog("close");
return false;
});
});
Thanks for any input, currently i’m getting a -1 value for the alert. If I leave out the selector for index it’ll show however many divs are apart of the index. I hope this makes sense, thank you again.
I would restructure your code. This is the framework that I came up with. I think that you can leverage it for your needs.
http://jsfiddle.net/v4dtL/
A few things:
Don’t use
live. It has been deprecated. Useonordelegateinstead.Add a class called modalized to the clicked element. This allows you to keep track of who launched the modal window without doing any funky DOM traversals.
Use jQuery’s
indexto find out the index of the clicked element in relation to its siblings.jQuery’s
dataobject allows you to store information on an element. So you could do something like this. Untested.