I have several dynamically created links and forms on one page named with IDs sub_comment_form_[id] and sub_add_comment_[id], respectively. I’m trying to:
- Hide all forms when the page loads
- Bind a click event to the link directly above the form to hide/show the form.
I’m not sure if there is a problem with my selectors, or if jQuery simply does not allow binding on multiple objects at once. Here is my code:
HTML
<a href="#" id="sub_add_comment_to_answer_[id]">Add comment</a>
<form id="sub_comment_form_to_answer_[id]"...
jQuery
$("form[ @id^='sub_comment_form' ]").hide();
$("a[ @id^='sub_add_comment' ]").click(function() {
var sibform = $(this).next("form");
if (sibform.is(':hidden')) {
$(this).text('Cancel');
sibform.slideDown('fast');
} else {
$(this).text('Add comment');
sibform.slideUp('fast');
}
});
If you’re using a newer version of jQuery (1.3+) there’s no
@on attribute selectors anymore, it just looks like this:This first one was also missing a closing brace, so be sure to fix that too 🙂
Also, be sure both of these are wrapped in a
document.readyhandler so they execute after the DOM is ready, like this:Alternatively, instead of these ID starts-with selectors you could use a class, for instance:
And bind it like this: