I have a question concerning using the toggle function. I have a template that is being populated at the end of an AJAX call with data returned from a web service. What I’m trying to accomplish is load the onClick function so that a hidden textbox will be shown and toggled to be hidden on the next click.
What’s happening is that when I click the link once everything’s fine the textbox shows and hides. But if I keep clicking the Edit link the textbox will show and hide the number of times that the link has been clicked (ie. I click the link for the second time it fadesIn/Out twice, the third time it fades In/Out 3 times, etc).
Would someone please look at my code and help me?
Thanks!
PS. I was also trying to toggle the link to go from “Edit” to “Cancel” as well; I haven’t spent much time on that but if you want to throw me a bone on that too, I’ll take it! 😉
function showSCs(data) {
$('#sometmpl3').tmpl(data.d)
.appendTo($('#subCats'))
.find(".aEdit").toggle(function() {
$(this).click(function() {
$(this).parent().find('.scEditHide').fadeIn();
$(this).text = "Cancel";
return false;
});
}, function() {
$(this).click(function() {
$(this).parent().find('.scEditHide').fadeOut();
return false;
});
});
}
The structure of the elements referenced is:
<div>
<h4>${ProblemSubCategory}</h4>
<input id="text${ProblemSubCategoryID}" type="text" value=${ProblemSubCategory} class="scEditHide"/>
<a href="#" id="${ProblemSubCategoryID}" class="aEdit">Edit</a>
<a href="dummyWebservice.asmx\DeleteSC\${ProblemSubCategoryID}">Delete</a>
</div>
Pointy is right about setting up the onClick handler. What you are doing now, is adding a new handler (that will be fired every time you click) to the element. That way, the first time you click it will add a handler and fire it. The second time you click, it will add yet another handler, and then fire both that and the one previously added.
You should change your code to something like this.