Reputation: 35
I am attempting to eventually create this page that will show a relative hidden list of data when a "plus" or "minus" image is clicked next an element that contains the list. Right now, as a button is clicked, all of the other buttons change in addition to the clicked button. I know this is because the .click() method is attached to every img with the src=plus.gif or src=minus.gif. However, I cannot figure out how to pass the correct img id into my function.
<script>
$( document ).ready(function() {
$("img[src='plus.gif']").click(function () {
$("img[src='plus.gif']").toggle();
$("img[src='minus.gif']").toggle();
});
$("img[src='minus.gif']").click(function () {
/*$("#siteList").toggle();*/
$("img[src='plus.gif']").toggle();
$("img[src='minus.gif']").toggle();
});
});
</script>
<h1><cfoutput>#qOrgSite.BUSINESS#</cfoutput></h1>
<cfloop list="#keysToStruct#" index="i">
<cfoutput>
<img src="plus.gif" id="plusImg_#i#" alt="" border="0">
<img src="minus.gif" id="minusImg_#i#" alt="" border="0" hidden>
<strong>#busStruct[i].name#</strong><br>
<div id="siteList" hidden>
<cfloop array="#busStruct[i].site#" index="j">
<cfoutput> #j#<br></cfoutput>
</cfloop>
</div>
</cfoutput>
</cfloop>
Upvotes: 1
Views: 333
Reputation: 936
I would strongly suggest you look into the .data() jquery element.
Here is one possiblity of how you could use it in your code:
<script>
$( document ).ready(function() {
$(".plusMinusImg").click(function () {
thisId = $(this).data("id");
console.debug(thisId);
$("#Section"+thisId).find(".plusMinusImg").toggle();
$("#Section"+thisId).find(".siteList").toggle();
});
});
</script>
<cfloop list="#keysToStruct#" index="i">
<cfoutput>
<div id="Section#i#">
<img src="plus.gif" data-id="#i#" class="plusMinusImg" alt="" border="0">
<img src="minus.gif" data-id="#i#" class="plusMinusImg" alt="" border="0" hidden>
<strong>#busStruct[i].name#</strong><br>
<div class="siteList" hidden>
<cfloop array="#busStruct[i].site#" index="j">
<cfoutput> #j#<br></cfoutput>
</cfloop>
</div>
</div>
</cfoutput>
</cfloop>
Upvotes: 2
Reputation: 171669
Always try to wrap repeating modules in a container. Then it is easy to traverse only within that container to isolate instances
<cfoutput>
<div class="myModuleContainer">
<img class="icon-plus" src="plus.gif" id="plusImg_#i#" alt="" border="0">
<img class="icon-minus" src="minus.gif" id="minusImg_#i#" alt="" border="0" hidden>
<strong>#busStruct[i].name#</strong><br>
<div id="siteList" hidden>
<cfloop array="#busStruct[i].site#" index="j">
<cfoutput> #j#<br></cfoutput>
</cfloop>
</div>
</div>
</cfoutput>
Then in your event handlers this
is the element that the event occurred on
$("img.icon-plus, img.icon-minus").click(function () {
$(this).closest('.myModuleContainer').find('.icon-plus, .icon-minus').toggle();
});
Upvotes: 1